2011-11-22 36 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