Search code examples
phpregexhtml-parsing

regex php - find value in div with specific ID


How can i do to find the content of this div with preg_match()?

The link to my page can be found here.

I want get the product value of this page. I did something like this but i can't get nothing:

if (!preg_match("<div id=\"productPrice\">(.*)<\/div>/si", $data, $dealer_price)) 
    return; 

I am also trying the following:

if (!preg_match("<div class=\"price\">(.*)<\/div>/si", $data, $dealer_price)) 
    return;

Thank you in advance for your help.


Solution

  • There are a few reasons your regular expression is not working as you expect.

    1. You supply no delimiter in the beginning of your expression.
    2. There is an attribute after your div @id attribute.
    3. * is a greedy operator, you should use *? to return a non-greedy match.
    4. If you want the value you need to return your captured group.

    To fix your regular expression:

    preg_match('~<div id="productPrice"[^>]*>(.*?)</div>~si', $data, $dealer_price);
    echo trim($dealer_price[1]); //=> "$249.95"
    

    Use DOM to grab the product value from your data, not regular expression.

    $doc = new DOMDocument;
    $doc->loadHTML($data);
    
    $xpath = new DOMXPath($doc);
    $node  = $xpath->query("//div[@id='productPrice']")->item(0);
    echo trim($node->nodeValue); //=> "$249.95"