php - making preg_replace not working inside html -


i struggling.. use simple code searching words in text , 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 1 of search pattern found between html inside $mytext. example:

$mytext="blablablabla <strong class="word1">sad</strong>"; 

as can see word1 css class link. if run preg_replace destroy every markup there.

how can edit $search pattern not matching inside html, like: [^<.?*>] ?

thanks

the simple-minded workaround is:

preg_replace("# [>][^<]*? \k \b(word1)\b #x", $replace, $txt); 

this ensures there's 1 closing > angle bracket before word. (and \k makes forget matched part). ever replace first occurence of word1 per enclosing tag / paragraph / etc.

so better solution use preg_replace_callback("/>([^<]+)/") , second word1|word2|word3 regex (your existing code) in callback function instead.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -