【问题标题】:Checking if any of the strings in an array matches a string检查数组中的任何字符串是否与字符串匹配
【发布时间】:2011-05-25 21:30:42
【问题描述】:

我正在尝试找出一个字符串是否与我的数组 IE 中的任何坏词匹配:

$badWords = Array('bad', 'words', 'go', 'here');
$strToCheck = "checking this string if any of the bad words appear";

if (strpos($strToCheck, $badWords)) { 
    // bad word found
}

问题是 strpos 只能检查一个字符串而不是一个数组,有没有一种方法可以做到这一点而不循环遍历 badwords 数组?

【问题讨论】:

标签: php


【解决方案1】:

不完全是,因为所有解决方案都不可避免地必须遍历您的数组,即使它在“幕后”。您可以使用 $badWords 制作正则表达式,但运行时复杂性可能不会受到影响。无论如何,这是我的正则表达式建议:

$badWordsEscaped = array_map('preg_quote', $badWords);
$regex = '/'.implode('|', $badWordsEscaped).'/';
if(preg_match($regex, $strToCheck)) {
  //bad word found
}

请注意,如果它们包含任何特殊的正则表达式字符,例如 /.,我已经对这些词进行了转义以防止正则表达式注入

【讨论】:

    【解决方案2】:

    array_intersect() 为您提供匹配单词列表:

    if (count(array_intersect(preg_split('/\s+/', $strToCheck), $badWords))) {
        // ...
    }
    

    【讨论】:

      【解决方案3】:

      in_array. 读错问题。

      最简单的实现是为每个坏词调用 strpos():

      <?php
      $ok = TRUE;
      foreach($badwords AS $word)
      {
          if( strpos($strToCheck, $word) )
          {
              $ok = FALSE;
              break;
          }
      }
      ?>
      

      【讨论】:

        【解决方案4】:

        试试这个..

        $badWords = array('hello','bad', 'words', 'go', 'here');
        $strToCheck = 'i am string to check and see if i can find any bad words here';
        //Convert String to an array
        $strToCheck = explode(' ',$strToCheck);
        
        foreach($badWords as $bad) {
            if(in_array($bad, $strToCheck)) {
                echo $bad.'<br/>';
            }
        }
        

        上面的代码会返回所有匹配的坏词,你可以进一步扩展它来实现你自己的逻辑,比如替换坏词等。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-05-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-08
          相关资源
          最近更新 更多