Php regular expression to match a div

Use an HTML parser. NOT regular expressions.

The problem with regular expressions is that they cannot match nested structures. Assuming your regex must match a single <div> and its closing tag, there is no way to correctly match this input:

<div id="a">
    <div id="b">
        Foo
    </div>
</div>
<div id="c">
    Bar
</div>

Because if your regular expression is greedy, it will match the two uppermost divs, and if it’s ungreedy, it will not match the correct end tag.

Therefore, you should use an HTML parser. With PHP, DOMDocument::loadHTML orDOMDocument::loadHTMLFile each do a fairly good job. (You may "safely" ignore the warnings it generates: they’re only markup errors, and the generated DOMDocument object should be pretty much okay.)

Since the PHP getElementById is a pain to get to work, you can use DOMXpath for the same purpose:

<?php

$url = "http://urlchecker.net/html/demo.html";

$d = new DOMDocument();
$d->loadHTMLFile($url);

$xpath = new DOMXPath($d);
$myNews = $xpath->query('//@id="news-id-160346"')->item(0);

?>

Source

http://stackoverflow.com/questions/2947360/php-regular-expression-to-match-a-div

Leave a comment