0

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.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
pramod24
  • 1,096
  • 4
  • 17
  • 38

3 Answers3

6

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"
hwnd
  • 69,796
  • 4
  • 95
  • 132
0

The regexes in preg need to be enclosed in delimiters, such as ~ or / etc. Also, you need to use lazy matching in your expression:

preg_match( "@<div id=\"productPrice\">(.*)</div>@siU", $data, $dealer_price )
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0
<?php
  $data = '<body><div id="productPrice">12.20</div></body>';
  if(!preg_match('/<div id="productPrice">(.*)<\/div>/si', $data, $dealer_price)) return;

  $dealer_price = $dealer_price[0];
  echo $dealer_price;
?>                  

hope this helps..

dano
  • 1,043
  • 1
  • 6
  • 11