用PHP regexp替换单词或单词组合


Replace words or words combinations with PHP regexp

我有替换词的映射:

$map = array(
  'word1' => 'replacement1',
  'word2 blah' => 'replacement 2',
  //...
);

我需要替换字符串中的单词。但是替换应该只在string为word:

时执行。
  • 它不在其他单词的中间,例如textword1不会被replacement1取代,因为它是另一个令牌的一部分。
  • 分隔符必须保存,但必须替换分隔符前后的单词。

我可以用regexp将字符串拆分为单词,但是当有少量标记的映射值(如word2 blah)时,这不起作用。

$map = array(   'foo' => 'FOO',
                'over' => 'OVER');
// get the keys.
$keys = array_keys($map);
// get the values.
$values = array_values($map);
// surround each key in word boundary and regex delimiter
// also escape any regex metachar in the key
foreach($keys as &$key) {
        $key = '/'b'.preg_quote($key).''b/';
}
// input string.    
$str = 'Hi foo over the foobar in stackoverflow';
// do the replacement using preg_replace                
$str = preg_replace($keys,$values,$str);