How to replace matching words from an associative array without replacing words within existing links

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
kressly
New php-forum User
New php-forum User
Posts: 1
Joined: Wed Jan 01, 2020 3:01 pm

Wed Jan 01, 2020 3:09 pm

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.

Code: Select all

<?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 an href tag within another one

Code: Select all

<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>
Demo sandbox.onlinephpfunctions.com/code/22a86a3bbba2c6b1a2f07de941ece93af7540241

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 ?
User avatar
hyper
php-forum GURU
php-forum GURU
Posts: 929
Joined: Mon Feb 22, 2016 5:52 pm

Wed Jan 01, 2020 5:20 pm

IMO you'll have to split it down to several steps as there are quite complicated rules to apply.

From what you have given, a possible process:

Start with any multiple keywords first, then you could use explode to spilt into single words and loop through the array for a search / replace, maybe str_replace and finally re-join the array using implode
Post Reply