pramod24
pramod24

Reputation: 1116

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.

Upvotes: 0

Views: 7172

Answers (3)

hwnd
hwnd

Reputation: 70722

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"

Upvotes: 6

dano
dano

Reputation: 1043

<?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..

Upvotes: 0

hjpotter92
hjpotter92

Reputation: 80639

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 )

Upvotes: 0

Related Questions