pee2pee
pee2pee

Reputation: 3792

PHP Regex to find matching div tags

Example: https://regex101.com/r/nHiyU3/1

CODE:

<div id="content">
    <div>
        <div class="col-image"></div> <!-- STOPS HERE -->
        THIS CONTENT HERE DOES NOT GET CAPTURED
    </div>
</div>

REGEX:

/<div id=[\'|"]content[\'|"][^>]*>(.*)<\/div>/sUi

So it stops where I've added the note to say

Any reason why? Have followed other topics on SO but can't get it to grab the whole lot.

So I know how to do it across multiple lines, it's finding the matching tag across multiple lines

Upvotes: 0

Views: 170

Answers (1)

William J.
William J.

Reputation: 1584

As mentioned in the comments, it's easier to achieve this using DOMDocument. For example:

<?php
    $html = '<div id="content"><div><div class="col-image"></div> <!--
             STOPS HERE -->THIS CONTENT HERE DOES NOT GET CAPTURED</div></div>';
    $domDocument = DOMDocument::loadHTML($html);
    $divList = $domDocument->getElementsByTagName('div');
    foreach ($divList as $div) {
        var_dump($div);
    }

Upvotes: 1

Related Questions