Re: problem with preg_replace

From: Date: Tue, 13 Jan 2004 18:00:10 +0000
Subject: Re: problem with preg_replace
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-174474@lists.php.net to get a copy of this message
Hello Gregor, On 13 Jan 2004 at 15:08, Gregor Jaksa wrote: > hello, i need to replace some words in file with [tag]word[/tag] and other > words with [sample]word[/sample]. > > i have a list of words which i need to replace with [sample] tags declared > like > $words = 'word1|word2|word3|word4'; > > replacing those words is easy i just use preg_replace('/\b( ' . $words . > ')\b/i', '[sample]$1[/sample]', $file); > but how to replace all other words that are not in $words array with [tag] > tag ? > > thx in advance! Let me see if I understood you correctly: you want to surround all the words in the string $file that are not also contained in the $words array with [tag] and [/tag]? Here's an idea: <?php $file = 'this is my test string and I just want to use it for a quick test'; $words = 'test|string'; $new_file = preg_replace('/\b('.$words.')\b/', ' [sample]$1[/sample] ', $file); $new_file = preg_replace('/\b(?<!\[sample\]|\[)(\w+)(?!\[\/sample\]|\])\b/', ' [tag]$1[/tag] ', $new_file); print $new_file; ?> Very important: you *must not* forget the spaces before and after the opening and closing brackets in the replacement string. Good luck, Erik

« previous php.general (#174474) next »