0

私はコードを持っています、

$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ますか?

4

1 に答える 1

3

これ によると、\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.

于 2012-09-26T13:22:54.470 に答える