-1

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 ?

Man Of God
  • 774
  • 2
  • 14
  • 32
  • The post associated with this post does even answer my question https://stackoverflow.com/questions/2165381/how-can-i-replace-strings-not-within-a-link-tag – Man Of God Jan 01 '20 at 22:18

1 Answers1

0

This should work:

preg_replace("/(^|[^a-zA-Z-0-9]+)(<a[^>]+>)?" . $name . "(<\/a>)?[^a-zA-Z-0-9]+/", " <a href='". $value . "' title='" . $name . "'>" . $name . "</a> ", $text);

If it's already a link, it will replace it completely.

Mindastic
  • 4,023
  • 3
  • 19
  • 20
  • This is good but it removes all the dots and coma in the string. Can you please fix it so i may mark this as the answer ? Here is a link to the whole thing with this solution. Here is a demo of what you posted http://sandbox.onlinephpfunctions.com/code/304073264b0881ed458a622ddbee857159c849d6 . If you help me fix it, I will accept it as answer – Man Of God Jan 01 '20 at 21:20