假设我有一系列坏词:
$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/