これ によると、\b
以外はサポートしていません[A-Za-z0-9_]
。
文字列から正規表現を生成しているため、正規表現をエスケープする必要があることに注意してください(そして、PHP コンパイラは、この文字列を作成する時点で、それが正規表現であることを知りません)。
正規表現を使用する/(^|\s)WORD($|\s)/i
とうまくいくようです。
コード例:
$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 = "/(^|\\s)" . preg_quote($word) . "($|\\s)/i";
$replace = " " . str_repeat('*', strlen($word)) . " ";
$text = preg_replace($pattern, $replace, $text);
}
echo $text;
出力:
This is a **** ***** *** ******* *** *** test with grass and passages.
文字列がこれらの単語のいずれかで開始または終了する場合、一致の両端にスペースが追加されることに注意してください。つまり、テキストの前後にスペースがあります。あなたはこれを処理することができますtrim()
アップデート;
また、これは句読点をまったく考慮していないことに注意してください。
the other user has an ass. and it is nice
たとえば、通過します。
これを克服するには、さらに拡張することができます。
/(^|\\s|!|,|\.|;|:|\-|_|\?)WORD($|\\s|!|,|\.|;|:|\-|_|\?)/i
これは、置換方法も変更する必要があることを意味します。
$text = "This is a $1ut ( Y ) @ss?@sshole you're an ass. a$$ ass test with grass and passages.";
$blacklist = array(
'$1ut',
'( Y )',
'@ss',
'@sshole',
'a$$',
'ass'
);
foreach ($blacklist as $word) {
$pattern = "/(^|\\s|!|,|\\.|;|:|\\-|_|\\?)" . preg_quote($word) . "($|\\s|!|,|\\.|;|:|\\-|_|\\?)/i";
$replace = '$1' . str_repeat('*', strlen($word)) . '$2';
$text = preg_replace($pattern, $replace, $text);
}
echo $text;
他のすべての句読点などを追加します。
出力:
This is a **** ***** ***?******* you're an ***. *** *** test with grass and passages.