CyberJ
CyberJ

Reputation: 1124

PHP preg_match_all of parent with class name

Using preg_match_all is it possible to match elements within a parent that has a specific class name?

For example I have this HTML markup:

<div class="red lorem-ipsum>
  <a href="#">Some link</a>
</div>

<div class="red>
  <a href="#">Some link</a>
</div>

<div class="something red lorem-ipsum>
  <a href="#">Some link</a>
</div>

Can I match each <a> that's within a parent with class name red?

I tried this but it does not work:

~(?:<div class="red">|\G)\s*<a [^>]+>~i

Upvotes: 0

Views: 518

Answers (1)

trincot
trincot

Reputation: 350365

Use DOMDocument in combination with DOMXPath. Here the HTML is in the $html variable:

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$matches = $xpath->query("//div[contains(concat(' ', @class, ' '), ' red ')]/a");
foreach($matches as $a) {
    echo $a->textContent;
}

Upvotes: 2

Related Questions