我有一個代碼,如何編寫正確的正則表達式來刪除列出話
$text = "This is a $1ut (Y) @ss @sshole a$$ ass test with grass and passages.";
$blacklist = array(
'$1ut',
'(Y)',
'@ss',
'@sshole',
'a$$',
'ass'
);
foreach ($blacklist as $word) {
$pattern = "/\b". preg_quote($word) ."\b/i";
$replace = str_repeat('*', strlen($word));
$text = preg_replace($pattern, $replace, $text);
}
print_r($text);
它會返回以下結果:
This is a $1ut (Y) @ss @sshole a$$ *** test with grass and passages.
當我從正則表達式中刪除字邊界,
$pattern = "/". preg_quote($word) ."/i";
返回:
This is a **** ***** *** ***hole *** *** test with gr*** and p***ages.
我如何寫正則表達式所以它不會取代這樣的話passages
,grass
等,但完全取代,如@sshole
?
應該補充說的是,無論你認爲帶有密碼和替換的單詞列表有多大幫助,人們總是會**試圖找到它,最終它們會。那麼它只會是assh0le或$$洞而已。 – h2ooooooo
是的,我知道。因爲這個單詞會增長。但我的問題是如何編寫正則表達式。這不僅可以用來防止罵人的話,而且可以用於任何類似的情況。 –
我認爲更重要的問題是爲什麼用\ b的它沒有找到你的單詞 – BugFinder