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

时间:2022-09-13 09:49:18

I have map for replacement words:

我有替换单词的地图:

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

I need to replace words in string. But replacement should be executed only when string is word:

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

  • It is not in the middle of some other word ex. textword1 will not be replaced with replacement1 because it is part of another token.
  • 它不在其他单词ex的中间。 textword1不会被replacement1替换,因为它是另一个令牌的一部分。

  • Separators must be saved, but words before/after them should be replaced.
  • 必须保存分隔符,但应替换它们之前/之后的单词。

I could split string with regexp to words but this does not work when there will be mapped values with few tokens (like word2 blah).

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

1 个解决方案

#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 *';

// do the replacement using preg_replace                
$str = preg_replace($keys,$values,$str);

See it

#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 *';

// do the replacement using preg_replace                
$str = preg_replace($keys,$values,$str);

See it