2014-10-03 29 views
0

想在數組列表只更換原話,目前的代碼工作指望它檢查全字內容和替換:(篩選確切的詞不是全字

例子: -

$字符串=這是一個測試,快樂測試

它將取代「試」爲T - 廷和測試爲T - T的

通緝出認沽: - 只能過濾測試爲T - T,忽略當過濾詞與其他包括字符

代碼

function filter($string) {    

    $wordlist = array(
       'test' => 't--t' 

    ); 
        foreach ($wordlist as $word => $filter) { 
         $word = "/{$word}/"; 
         preg_match_all($word, $string, $matches); 
          foreach ($matches[0] as $bword) { 
           $pattern = "/{$bword}/"; 
           $string = preg_replace($pattern, $filter, $string); 
          } 
        } 

    return $string; 
} 

echo filter($string); 

我覺得模式是不正確的,能不能幫我找到正確的模式或任何工作代碼applicate

回答

0

假設Extract = Exact =錯字?

如果您想匹配確切的單詞,請使用word boundaries

/\btest\b/匹配「確切」test。還要匹配無情的添加iflag/\btest\b/i

另請注意,您可以使用preg_replace() function的數組。所以功能可能是:

$string= "This is a testing ,Happy test"; 

function filter($string) 
{    
    $wordlist = array(
    '/\btest\b/' => 't--t' 
); 

    return preg_replace(array_keys($wordlist), array_values($wordlist), $string); 
} 

echo filter($string); 

Test at eval.in

+0

不工作的非英文字符/詞 – 2014-10-03 11:01:10

+0

@Randy Suitt您的意見是utf-8?比使用'u' [modifier](http://php.net/manual/en/reference.pcre.pattern.modifiers.php):'/ \ btest \ b/u'注意,pattern和input都有如果是的話就是utf-8。或者'/ \ btest \ b/ui'用於utf-8和無格式匹配。 – 2014-10-03 11:02:51

+0

@RandySuitt如果在編輯器中輸入ASCII並輸入UTF-8,則只需要utf-8對圖案進行編碼。 ' '/\b'.utf8_encode("wörd「)。' \ B/ui'' – 2014-10-03 11:11:35