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

时间:2011-11-22 08:58:21

标签: php regex replace

我有替换字的地图:

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

我需要替换字符串中的单词。但是只有当字符串是单词时才应该执行替换:

  • 它不在其他单词的中间。 textword1 不会被 replacement1 替换,因为它是另一个令牌的一部分。
  • 必须保存分隔符,但应替换它们之前/之后的单词。

我可以将带有正则表达式的字符串拆分为单词,但是当存在少量标记的映射值时(例如 word2 blah ),这不起作用。

1 个答案:

答案 0 :(得分:5)

$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);

See it

相关问题