Regex Preg_match_all search

Hello all,

I really don’t know how to do this, so please help me out :wink:

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! :slight_smile:

Greetings,
xtaste

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

/*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:


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:


Array
(
    [0] => Array
        (
            [0] => aaaaaaaaaaaa
            [1] => 1111111111111111
        )

    [1] => Array
        (
            [0] => bbbbbbbbbbbb
            [1] => 2222222222222222
        )

    [2] => Array
        (
            [0] => cccccccccccc
            [1] => 3333333333333333
        )

)

Thanks for your response :slight_smile:

Ok, I already thought there wouldn’t be another way to do it. :wink:

I’ll use this solution for my program, thanks again! :slight_smile: