SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2011
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regex Preg_match_all search

    Hello all,

    I really don't know how to do this, so please help me out

    I want to do a preg_match_all on this:

    <ul>
    <li><span>Label</span>Content</li>
    <li><span>Label</span>Content</li>
    <li><span>Label</span>Content</li>
    ...
    </ul>

    I want to retrieve the labels and contents.

    Is there a way to do this with preg_match_all only?

    Thanks!

    Greetings,
    xtaste

  2. #2
    SitePoint Enthusiast
    Join Date
    Feb 2012
    Location
    United Kingdom
    Posts
    77
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    This can be done by looping through each of the <li> tags you have, and then grabbing the contents desired. Here's the corresponding code:

    PHP Code:
    <?php

    /*dummy text*/
    $a = <<< 'end'
    <ul>
     <li><span>aaaaaaaaaaaa</span>1111111111111111</li>
     <li><span>bbbbbbbbbbbb</span>2222222222222222</li>
     <li><span>cccccccccccc</span>3333333333333333</li>
     </ul>
    end;

    $f preg_match_all('#<li>.+?</li>#is'$a$matches);

    $done = array();

    foreach(
    $matches[0] as $match)
    {
        
    preg_match_all('#<li><span>(.*?)</span>(.*?)</li>#i'$match$m);

        
    $done[] = array($m[1][0], $m[2][0]);
    }

    for(
    $b=0;$b<=$f-1;$b++)
    {
        echo 
    'Span content: ',$done[$b][0],'<br />After span tag content: ',$done[$b][1],'<br /><br />';
    }
    # done[$b][0] = span tag content
    # done[$b][1] = after span tag content

    ?>
    The above will output:
    Code:
    Span content: aaaaaaaaaaaa
    After span tag content: 1111111111111111
    
    Span content: bbbbbbbbbbbb
    After span tag content: 2222222222222222
    
    Span content: cccccccccccc
    After span tag content: 3333333333333333
    Here's the a visual view of the array being produced:
    Code:
    Array
    (
        [0] => Array
            (
                [0] => aaaaaaaaaaaa
                [1] => 1111111111111111
            )
    
        [1] => Array
            (
                [0] => bbbbbbbbbbbb
                [1] => 2222222222222222
            )
    
        [2] => Array
            (
                [0] => cccccccccccc
                [1] => 3333333333333333
            )
    
    )

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2011
    Posts
    50
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your response

    Ok, I already thought there wouldn't be another way to do it.

    I'll use this solution for my program, thanks again!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •