在字符串preg_match数组项?数组、字符串、preg_match

2023-09-10 23:41:32 作者:在乎永远不够多り

可以说我有不好的话数组:

Lets say I have an array of bad words:

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

和随机字符串:

$string = "some variable text";

如何建立这个循环:

How to create this cycle:

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";

例: 如果 $字符串=一个晴朗的一天或某一天我们两个做了,用户应该看到抱歉不好的词发现的消息。 如果 $字符串=青天白日,用户应该看到的字符串中不包含脏话的消息。

Example: if $string = "one fine day" or "one fine day two of us did something", user should see sorry bad word found message. If $string = "fine day", user should see string contains no bad words message.

据我所知,你不能 preg_match 的数组。有何意见?

As I know, you can't preg_match from array. Any advices?

推荐答案

这个怎么样:

$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 { ... }