我有一些簡單的代碼,做了預浸比賽:如何在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
然後我把它放在數組則數組做它的工作中,但這似乎並沒有工作。
可以把'array_map'方法放入'public static function cleanStr($ str)()'方法嗎?或者是'$ el'數組或壞字? – Patrioticcow 2012-08-01 01:48:55
'$ el'是一個單獨的數組元素。你可以把邏輯放入一個函數中,但你並沒有清理一個字符串,而是將'$ bad_words'數組轉換成一個更好的正則表達式,它能夠替換許多混淆。 – nickb 2012-08-01 01:50:33
以此字符串爲例:'我喜歡頁面頂部帶有標題的字典,也在fuccillo現代店購物!'這裏沒有不好的字眼。然而,它會返回'我愛***的***在頁面頂部,也在*** cillo現代店!'而且在你的第一個代碼塊中它應該是'$ match [0]'而不是'$ match [1]'。 – 2012-08-01 01:51:58