25

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.

3 Answers 3

75
preg_match("'<p class=\"review\">(.*?)</p>'si", $source, $match);
if($match) echo "result=".$match[1];
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't this likely to overmatch? See my answer below.
It won't overmatch because of lazy quantification. .*? will grab as less as possible, while .* would grab as much as possible.
11

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 

Comments

8

What if the string you're matching has multiple lines and is:

<p class="review"> Desired text1 </p>
<p class="review"> Desired text2 </p>
<p class="review"> Desired text3 </p>

That pattern would match once, and the match would be everything in the string.

I think a better pattern is:

"'<p class=\"review\">([^<]*)</p>'si"

1 Comment

yes, thanks, i've been trying stuff for the past 2 hours and I finally realised that the stocks are being displayed with JavaScript, after the page is loading :((( so yey, that's why the script was not working thanks all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.