Abdul Jabbar
Abdul Jabbar

Reputation: 5931

Find and extract Matched values from String in PHP

I have a text like below

$str = '<div>
           <div id="priceRangeWrapper">
              <div id="priceSlider" min="0" max="0"></div>
           </div>
        </div>';

1) First I want to get the position of <div id="priceSlider" min="0" max="0"></div> from above string where min and max values are random. Something like with strpos() function of Php in which it returns the position in terms of int like

 $pos = strpos($str, '<div id="priceSlider" min="0" max="0"></div>');
 //but min and max values are random. I don't know what can be they

2) I want to get min and max values from above text. How can I get these two values with/without regex in PHP?

Upvotes: 0

Views: 53

Answers (1)

nickb
nickb

Reputation: 59699

Don't use a regex to parse HTML. Instead, here's an example with DOMDocument.

$doc = new DOMDocument();
$doc->loadHTML($str); // Load the HTML string from your post

$xpath = new DOMXPath($doc);
$node = $xpath->query('//div[@id="priceSlider"]')->item(0); // Get the <div>

// Print out the min and max attribute values
echo $node->getAttribute('min') . " " . $node->getAttribute('max');

You can see it working here.

Upvotes: 5

Related Questions