Answer the question
In order to leave comments, you need to log in
PHP DomDocument: how to process all links on a page?
Hello!
Can you please tell me how to process all links on the page (for example, add the “foo” class to them), and return them to their places in the text?
<?php
$content = <<<EOD
<p>Lorem <a href="#">ipsum</a> dolor sit amet, consectetur adipisicing elit. Explicabo porro illum nesciunt. <a href="#">Voluptatem</a>, blanditiis esse, quod <a href="#">expedita</a> repellendus consequuntur dolore pariatur dicta tempora facere sint labore at magnam, rem assumenda.</p>
<p>Commodi, expedita? <a href="#">Accusantium reiciendis</a> in voluptatem veniam ullam! Et, porro architecto in dicta maxime blanditiis iusto, totam quis rerum voluptas numquam vero doloremque! Itaque impedit eligendi dignissimos, et <a href="#">veritatis eius</a>.</p>
EOD;
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($content);
$xpath = new DOMXPath($dom);
$links = $xpath->query('//a');
foreach($links as $link) {}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question