I have the following text:
“This is a test text. Test, comma instead of space.”
I iterate through each word and want to replace each word to a distinct link. Let’s say
<a href="wordToReplace">wordToReplace</a>
My problem is that consecutive matches of the word “test” (to use the above example) replace the href and anchor text so I’m left with links inside links which is not good at all.
(to give a base idea of my problem this is what I’m left with. It has some additional markup.)
This is a<a href="/index.php?r<a href="/index.php?r=texts/addWord"
class="wordLink info label" id="yt2">text</a>/addWord" class="wordLink
info label" id="yt1">test</a>text.<a href="/index.php?r=texts/addWord"
class="wordLink info label" id="yt3">Test</a><a
href="/index.php?r=texts/addWord" class="wordLink info label"
id="yt4">comma</a>instead of<a href="/index.php?r=texts/addWord"
class="wordLink info label" id="yt6">space</a>
I’m trying
preg_replace("/[^\">]".$word."[^\"<]/", $link, $text->text);
but I don’t think I’m on the right track at all.
Thanks for the time
From your one line of code, I’m assuming that you have that line in a loop which iterates through all the
$wordsyou want to replace, which causes the problem.What you need to do is put all those replacements into only one
preg_replacecall. For that, regexes provide alternatives. So say, your list of words consisted oftest,textandthis. Then you could do:And if you have all your words in an array
$wordsthen you can generate the regex simply with:You might want to add an
iat the very end of your regex, if your checks are supposed to be case-insenstive.In case some of your words are parts of other words (e.g. you want to replace
textandtexture), you could check for word boundaries:Is this what you are looking for?
EDIT: If your
$linkwas pre-generated for every$wordin your loop before, you can now replace that word with$1. If your$linkwas something likeyou can now simply use