使用PHP正则表达式替换单词或单词组合

4
我有一个替换词的映射表:
$map = array(
  'word1' => 'replacement1',
  'word2 blah' => 'replacement 2',
  //...
);

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

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

我可以使用正则表达式将字符串拆分成单词,但是当有几个标记具有映射值(例如 word2 blah)时,这种方法无法起作用。


3
不确定它是否能单独完成任务,但您可能想要查看单词边界 \b。 - Corbin
1个回答

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接