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.

我怎样才能编写正则表达式,这样它就不会替换诸如等之类的词passagesgrass而是完全替换诸如之类的词@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 回答