php - preg_match 字符串中的数组项?

标签 php algorithm preg-match string-parsing

假设我有一系列坏词:

$badwords = array("one", "two", "three");

和随机字符串:

$string = "some variable text";

如何创建这个循环:

if (one or more items from the $badwords array is found in $string)
echo "sorry bad word found";
else
echo "string contains no bad words";

例子:
如果 $string = "one fine day"或 "one fine day two of us did something",用户应该看到抱歉的坏词发现消息。
如果 $string = "fine day",用户应该看到 string contains no bad words 消息。

据我所知,您不能从数组中preg_match。有什么建议吗?

最佳答案

这个怎么样:

$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';

$noBadWordsFound = true;
foreach ($badWords as $badWord) {
  if (preg_match("/\b$badWord\b/", $stringToCheck)) {
    $noBadWordsFound = false;
    break;
  }
}
if ($noBadWordsFound) { ... } else { ... }

关于php - preg_match 字符串中的数组项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10358300/

相关文章:

php - 如何在 PHP 项目中找到未使用的函数

尝试插入几个值时 PHP/MySQL 语法错误

php - 在 php 中处理新行

php - 对应于 Python 中 PHP 的 preg_match

php - 分隔符不能是字母数字或反斜杠和 preg_match

php - 我应该什么时候删除用户的登录 cookie?

python - 我可以在字符串上使用 K-means 算法吗?

algorithm - 生成给定长度的 0's and 1' 的所有组合,最小和最大为 1

骰子问题的算法

php - 从文本中提取 4 位数字