0

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
3
  • Use a parser...it will be easier, and more accurate. Commented Feb 22, 2019 at 20:03
  • DOMDocument is a much better way, use XPath (with stackoverflow.com/questions/8680721/…). Commented Feb 22, 2019 at 20:06
  • @user3783243 parser? Commented Feb 22, 2019 at 20:28

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the code!I have not tried DOMXPath before. Where am I selecting the <a>? is it the /a at the end?
Yes, indeed: / means "child" (// is "descendant"), and "a" is the tag name. The more complex part is to match a class. More about that part here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.