I am struggling.. I use this simple code for searching words in text开发者_如何学C and add relevant texts:
$search=array("/\bword1\b/","/\bword2\b/","/\bword3\b/");
$replace=array("<a href='link1'>word1</a>",ecc);
preg_replace($search,$replace,$myText);
Problem comes when one of the search pattern is found between a html inside $myText. Example:
$myText="blablablabla <strong class="word1">sad</strong>";
As you can see word1 is a css class for the link. If i run the preg_replace will destroy every markup there.
How can I edit my $search pattern for not matching inside html, something like: [^<.?*>] ?
Thanks
The simple-minded workaround is:
preg_replace("# [>][^<]*? \K \b(word1)\b #x", $replace, $txt);
This ensures that there's one closing >
angle bracket before the word. (And \K
makes it forget that matched part). However it will only ever replace the very first occurence of word1
per enclosing tag / paragraph / etc.
So a much better solution would be to use preg_replace_callback("/>([^<]+)/")
and the second word1|word2|word3
regex (your existing code) in the callback function instead.
精彩评论