I have a string containing sentences made of keywords that must be replaced with a link. I also have an associative array containing some of those keywords and the urls each keyword must be linked to by replacement. I am able to replace the words but the problem is that when an existing link already existed in the string, it creates a link within the link tags.
<?php
$text='Jesus is Lord and this text contains mainy keywords, and the <a href="#words" title="words">words</a> that Jesus spoke to us are Spirit and words of life. That is why you have to learn how to hear from God.';
$keywords = array(
'Jesus' => 'https://www.iusefaith.com',
'words' => 'words-53',
'keywords' => 'keywords-27',
'Hear From God' => 'hear-from-god-94',
// and etc...
);
######################################
foreach($keywords as $name => $value)
{
$text = preg_replace('~\b'. $name.'\b~', "<a href='$value' title='$name'>$name</a>", $text);
}
#########################################################
echo $text;
?>
Executing this code gives a wrong tag for one of the links with the word words because that word was already a link in the string. So i get
<a href="#<a href='words-53' title='words'>words</a>" title="<a href='words-53' title='words'>words</a>"><a href='words-53' title='words'>words</a></a>
This outputs a link within a link and you can check a demo here.
How to replace matching words from an associative array without replacing words within existing links ? How to avoid replacing words when they are part of an existing links ?