1

I'm trying to add link to keyword with php dom method but the problem is that it's adding links on all instances it can find. I want to skip when keyword already have a link or it's inside img alt="" or title="" attribute, similarly inside any other tag or css class.

The issue is quite similar to this one. PHP simple html dom parser - find word

I tried the answer mentioned in last post with $tagsToExclude array but that's not working.

Here is the code.

<?php
require_once 'simple_html_dom.php';

$html = new simple_html_dom();
$html = str_get_html('<html><body><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

<p>Don\'t add link on Lorems</p>

<p>Add on Lorem again.</p>

<p>An existing link on <a href="http://lorem.net">Lorem</a></p>


<img src="Lorem.jpg" alt="Lorem text" title="Lorem image"></body></html>');


$nodes = $html->find('*');

$tagsToExclude = [
    "a",
    "img"
];

foreach($nodes as $node) {

    $keyword = 'Lorem';
    $link = '<a href="http://example.com">'.$keyword.'</a>';

    if (!in_array($node->tag, $tagsToExclude)) {

        if(strpos($node->innertext, $keyword) !== false) {
            $node->innertext = preg_replace('/\b'.$keyword.'\b/', $link, $node->innertext);
        }
    }
}

echo $html->outertext;
?>

Thanks

0

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.