【问题标题】:Check If string contains any of the words检查字符串是否包含任何单词
【发布时间】:2014-12-16 08:10:36
【问题描述】:

我需要检查一个字符串是否包含任何一个被禁止的词。我的要求是:

  1. 不区分大小写,这就是我使用stripos() 的原因
  2. 单词应该用空格分隔,例如如果禁用词是“poker”,“poker game”或“game poker match”应该在禁用字符串下,“trainpokering great”应该在good字符串下。

我尝试过类似下面的方法

$string  = "poker park is great";

if (stripos($string, 'poker||casino') === false) 
{

echo "banned words found";
}
else

{
echo $string;
}

【问题讨论】:

  • 4 个答案!没有按预期工作,欢迎任何其他答案
  • 抱歉,我的解决方案 (if (preg_match("/\b(poker|casino)\b/i", $string)) ) 仅适用于您的所有用例... :-) 例如,“扑克”、“扑克游戏”或“游戏扑克比赛”被标记为被禁止了,并且“trainpokering great”被标记为好......你为什么说它没有?

标签: php regex


【解决方案1】:
$string  = "park doing great with pokering. casino is too dangerous.";
$needles = array("poker","casino");
foreach($needles as $needle){
  if (preg_match("/\b".$needle."\b/", $string)) {
    echo "banned words found";
    die;
  }
}
echo $string;
die;

【讨论】:

  • 当字符串是 Pokering 时,它仍然说它被禁止了
  • 我想你现在已经解决了你的问题。通过向声明的数组 $needles 添加禁用词,您还可以检查它是否有多个词。
  • 修改不区分大小写的匹配 ... if (preg_match("/\b".$needle."\b/i", $string)) ...
【解决方案2】:

使用preg_match 匹配正则表达式:

$string  = "poker park is great";

if (preg_match("/(poker|casino)/", $string)) {
  echo "banned words found";
} else {
  echo $string;
}

更新:如 cmets 和 Mayur Relekar 回答中所建议的那样,如果您希望匹配不区分大小写,则应在正则表达式中添加 i 标志。
而且,如果您想匹配 words(即,“poker”前后应有一个词边界,例如空格、标点符号或文件结尾),您应将您的匹配组与\b...
所以:

...
if (preg_match("/\b(poker|casino)\b/i", $string)) {
...

【讨论】:

  • 为什么会得到 +6 ?这是区分大小写的,, -1
【解决方案3】:

MarcoS 是对的,除了在您的情况下您需要匹配确切的字符串而不是未绑定的字符串。为此,您需要为要完全匹配的字符串添加前缀和后缀 \b\b 是单词分隔符)。

$string  = "poker park is great";
if (preg_match("/\bpoker\b/", $string)) {
    echo "banned words found";
} else {
    echo $string;
}

【讨论】:

  • 它工作正常,但@DevakiArulmami 希望它适用于多个被禁止的单词,所以我只是修改了代码。
【解决方案4】:

你可以使用一个数组并加入它

$arr = array('poker','casino','some','other', 'word', 'regex+++*much/escaping()');
$string = 'cool guy';

for($i = 0, $l = count($arr); $i < $l; $i++) {
    $arr[$i] = preg_quote($arr[$i], '/');   // Automagically escape regex tokens (think about quantifiers +*, [], () delimiters etc...)
}
//print_r($arr); // Check the results after escaping

if(preg_match('/\b(?:' . join('|', $arr). ')\b/i', $string)) { // now we don't need to fear 
    echo 'banned words found';
} else {
    echo $string;
}

它使用单词边界并加入数组。

【讨论】:

  • 这里面怎么实现多词?
  • 抱歉,此代码不再适用于“dangerous game is poker”之类的字符串。 @DevakiArulmami
  • PO 没有谈到速度限制...如果这不是特定要求,我会避免使用“技巧”(在字符串中添加空格)...如果前面有单词怎么办/后跟标点符号?这个解决方案看起来相当“限制性”,至少...... :-)
  • @DevakiArulmami 现在我想它可以做你想做的事了。
  • @AmitJoki 我也会使用preg_quote()
猜你喜欢
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 2013-12-23
  • 1970-01-01
  • 2011-05-20
相关资源
最近更新 更多