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

Paw*_*wka 4 php regex replace

我有替换单词的地图:

$map = array(
  'word1' => 'replacement1',
  'word2 blah' => 'replacement 2',
  //...
);
Run Code Online (Sandbox Code Playgroud)

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

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

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

cod*_*ict 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);
Run Code Online (Sandbox Code Playgroud)

看见