I am trying to create a link tag <a href="{url}" title="{keyword}">keyword</a>
onto a given text when it find that keyword. But that keyword should NOT already inside an <a></a>
tag already and it should also not match href and title attribute. I'm using PHP
For example:
*NOTE. My usecase text don't have space
Text = <p>thisiscatfish</p>
Keyword = catfish
Expected Output = <p>thisis<a href="#" title="catfish">catfish</a></p>
BUT if
Text = <p>iam<a href="www.catfish.com" title="catfish">catfish</a></p>
Keyword = fish
Expected Output: <p>iam<a href="www.catfish.com" title="catfish">catfish</a></p>
*NOTE it should NOT match href and title attribute and replace it.
What I have tried https://paiza.io/projects/WYvDVTUMDg0kFOUo6NEHpQ
Problem
My solution so far it matching and replacing href and title as well. How can I modify my regex to not match href and title attribute as well?
function replaceText($text, $keyword, $url) {
$pattern = "/(?!>)$keyword(?!<\/a>)/i";
$replaceWith = "<a href='$url' title='$keyword'>$keyword</a>";
$newText = preg_replace($pattern, $replaceWith, $text);
return $newText;
}
$text = '<p>thisiscatfish</p>';
$newText = replaceText($text, 'catfish', 'www.catfish.com');
$newText2 = replaceText($newText, 'fish', 'www.fish.com');
echo $newText2;