Hot to replace words with preg_replace without duplicates

From: Date: Sat, 18 Dec 2010 19:03:21 +0000
Subject: Hot to replace words with preg_replace without duplicates
Groups: php.general 
Request: Send a blank email to php-general+get-310127@lists.php.net to get a copy of this message
Hi there, I want to create a function which will replace certain words out of a text with internal links. That works so far, but if I have two matches, I end up with invalid html code. Example: Welpen /hunde Chihuahua Welpen /hunde,chihuahua function seo_internal_links($str, $links, $limit) { foreach($links AS $link){ $pattern[$k] = "~\b($link[phrase])\b~i"; $replace[$k] = '<a href="'.$link[link].'">\\1</a>'; $k++; } return preg_replace($pattern,$replace,$str, $limit); } seo_internal_links($ad[text], $seo_internal_links, $limit = 1); This will result in: <a href="//hunde,chihuahua">Chihuahua <a href="/hunde">Welpen</a></a> Has somebody an idea on how to avoid this? I would also like to limit the amount of hits, but the limit in preg_replace accounts only for unique words, not the whole array. Thank you for any hint, Merlin

« previous php.general (#310127) next »