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

用PHP regexp替换单词或单词组合,php,regex,replace,Php,Regex,Replace,我有替换词的地图: $map = array( 'word1' => 'replacement1', 'word2 blah' => 'replacement 2', //... ); 我需要替换字符串中的单词。但仅当字符串为word时才应执行替换: 它不在其他单词的中间。TeXWord1不会被替换为替换,因为它是另一个令牌的一部分。 必须保存分隔符,但应替换分隔符前/后的文字 我可以将带有regexp的字符串拆分为单词,但当存在带有少量标记的映射值(如word2

我有替换词的地图:

$map = array(
  'word1' => 'replacement1',
  'word2 blah' => 'replacement 2',
  //...
);
我需要替换字符串中的单词。但仅当字符串为word时才应执行替换:

    它不在其他单词的中间。TeXWord1不会被替换为替换,因为它是另一个令牌的一部分。
  • 必须保存分隔符,但应替换分隔符前/后的文字
我可以将带有regexp的字符串拆分为单词,但当存在带有少量标记的映射值(如word2 blah)时,这不起作用


不确定它是否能自己完成这项工作,但您可能需要查看单词boundary\b。
$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);