2011-11-22 82 views
4

我有地图替换词:替换单词或单词组合与PHP的正则表达式

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

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

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

我可以用正则表达式来分割的话,但是串的时候会有很少的标记映射值,这并不工作(如单词2等等)。

+3

不知道它是否会通过自身做的工作,但你可能会想看看单词边界\湾 – Corbin

回答

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

相关问题