2012-08-01 107 views
0

我有一些簡單的代碼,做了預浸比賽:如何在PHP中的字符串做preg_replace?

$bad_words = array('dic', 'tit', 'fuc',); //for this example i replaced the bad words 

for($i = 0; $i < sizeof($bad_words); $i++) 
{ 
    if(preg_match("/$bad_words[$i]/", $str, $matches)) 
    { 
     $rep = str_pad('', strlen($bad_words[$i]), '*'); 
     $str = str_replace($bad_words[$i], $rep, $str); 
    } 
} 
echo $str; 

所以,如果$str"dic"的結果將是「*」等。

現在有一個小問題,如果$str == f.u.c。該解決方案可能是使用:

$pattern = '~f(.*)u(.*)c(.*)~i'; 
$replacement = '***'; 
$foo = preg_replace($pattern, $replacement, $str); 

在這種情況下,我會得到***,在任何情況下。我的問題是把所有這些代碼放在一起。

我已經試過:

$pattern = '~f(.*)u(.*)c(.*)~i'; 
$replacement = 'fuc'; 
$fuc = preg_replace($pattern, $replacement, $str); 

$bad_words = array('dic', 'tit', $fuc,); 

for($i = 0; $i < sizeof($bad_words); $i++) 
{ 
    if(preg_match("/$bad_words[$i]/", $str, $matches)) 
    { 
     $rep = str_pad('', strlen($bad_words[$i]), '*'); 
      $str = str_replace($bad_words[$i], $rep, $str); 
    } 
} 
echo $str; 

的想法是,$fuc成爲fuc然後我把它放在數組則數組做它的工作中,但這似乎並沒有工作。

回答

3

首先,你可以做一個(動態生成的)正則表達式的壞詞替換的所有,就像這樣:

$bad_words = array('dic', 'tit', 'fuc',); 

$str = preg_replace_callback("/\b(?:" . implode('|', $bad_words) . ")\b/", 
    function($match) { 
     return str_repeat('*', strlen($match[0])); 
}, $str); 

現在,你的人之間的加入時間問題單詞,您可以使用另一個正則表達式搜索並替換它們。但是,您必須記住.與正則表達式中的任何字符匹配,並且必須轉義(使用preg_quote()或反斜槓)。

$bad_words = array_map(function($el) { 
    return implode('\.', str_split($el)); 
}, $bad_words); 

這將創建一個$bad_words數組類似於:

array(
    'd\.i\.c', 
    't\.i\.t', 
    'f\.u\.c' 
) 

現在,你可以使用這個新$bad_words陣列就像上面的一個替換這些模糊的。

提示:您可以使此array_map()調用「更好」,因爲它可以更聰明地捕獲更多混淆。例如,如果你想趕上一個壞詞與句點或空白字符或逗號分隔,你可以這樣做:

$bad_words = array_map(function($el) { 
    return implode('(?:\.|\s|,)', str_split($el)); 
}, $bad_words); 

現在,如果你作出這樣的混淆組可選,你會趕上很多更糟糕的話:

$bad_words = array_map(function($el) { 
    return implode('(?:\.|\s|,)?', str_split($el)); 
}, $bad_words); 

現在,壞的話應該匹配:

f.u.c 
f,u.c 
f u c 
fu c 
f.uc 

等等。

+0

可以把'array_map'方法放入'public static function cleanStr($ str)()'方法嗎?或者是'$ el'數組或壞字? – Patrioticcow 2012-08-01 01:48:55

+0

'$ el'是一個單獨的數組元素。你可以把邏輯放入一個函數中,但你並沒有清理一個字符串,而是將'$ bad_words'數組轉換成一個更好的正則表達式,它能夠替換許多混淆。 – nickb 2012-08-01 01:50:33

+0

以此字符串爲例:'我喜歡頁面頂部帶有標題的字典,也在fuccillo現代店購物!'這裏沒有不好的字眼。然而,它會返回'我愛***的***在頁面頂部,也在*** cillo現代店!'而且在你的第一個代碼塊中它應該是'$ match [0]'而不是'$ match [1]'。 – 2012-08-01 01:51:58