Preg match text in php between html tags


Question

Hello I would like to use preg_match in PHP to parse the "Desired text" out of the following from a html document

<p class="review"> Desired text </p>

Ordinarily I would use simple_html_dom for such things but on this occasion it cannot be used (the above element doesn't appear in every desired div tag so I'm forced to use this approach to keep track of exactly when it doesn't appear and then adjust my array from simple_html_dom accordingly).

Anyway, this would solve my problem.

Thanks so much.

1
20
10/19/2009 3:00:48 AM

Accepted Answer

preg_match("'<p class=\"review\">(.*?)</p>'si", $source, $match);
if($match) echo "result=".$match[1];
67
10/19/2009 3:04:54 AM

if you want to return multiple matches then need to use preg_match_all(). You then loop through the second result group ($match[1]) to get just the content between tags.

$source = "<p class=\"review\"> Desired text1 </p>".
"<p class=\"review\"> Desired text2 </p>".
"<p class=\"review\"> Desired text3 </p>";


    preg_match_all("'<p class=\"review\">(.*?)</p>'si", $source, $match);

    foreach($match[1] as $val)
    {
        echo $val."<br>";


    }

Outputs:

Desired text1
Desired text2
Desired text3 

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon