考虑:

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

假设我有上面的代码,如果($a包含“are”),写语句的正确方法是什么?


当前回答

如果要检查字符串是否包含多个特定单词,可以执行以下操作:

$badWords = array("dette", "capitale", "rembourser", "ivoire", "mandat");

$string = "a string with the word ivoire";

$matchFound = preg_match_all("/\b(" . implode($badWords,"|") . ")\b/i", $string, $matches);

if ($matchFound) {
    echo "a bad word has been found";
}
else {
    echo "your string is okay";
}

例如,这对于在发送电子邮件时避免垃圾邮件非常有用。

其他回答

我在这方面遇到了一些麻烦,最后我选择了自己的解决方案。不使用正则表达式引擎:

function contains($text, $word)
{
    $found = false;
    $spaceArray = explode(' ', $text);

    $nonBreakingSpaceArray = explode(chr(160), $text);

    if (in_array($word, $spaceArray) ||
        in_array($word, $nonBreakingSpaceArray)
       ) {

        $found = true;
    }
    return $found;
 }

您可能会注意到,前面的解决方案并不是对另一个用作前缀的单词的答案。为了使用您的示例:

$a = 'How are you?';
$b = "a skirt that flares from the waist";
$c = "are";

对于上面的示例,$a和$b都包含$c,但您可能希望函数告诉您,只有$a包含$c。

可以使用以下函数检查字符串:

function either_String_existor_not($str, $character) {
    return strpos($str, $character) !== false;
}

另一个选项是使用strstr()函数。类似于:

if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}

注意:strstr()函数区分大小写。对于不区分大小写的搜索,请使用stristr()函数。

检查字符串是否包含特定单词?

这意味着字符串必须解析为单词(请参见下面的注释)。

执行此操作并指定分隔符的一种方法是使用preg_split(doc):

<?php

function contains_word($str, $word) {
  // split string into words
  // separators are substrings of at least one non-word character
  $arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);

  // now the words can be examined each
  foreach ($arr as $value) {
    if ($value === $word) {
      return true;
    }
  }
  return false;
}

function test($str, $word) {
  if (contains_word($str, $word)) {
    echo "string '" . $str . "' contains word '" . $word . "'\n";
  } else {
    echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
  }
}

$a = 'How are you?';

test($a, 'are');
test($a, 'ar');
test($a, 'hare');

?>

跑一次就可以

$ php -f test.php                   
string 'How are you?' contains word 'are' 
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'

注意:这里我们不是指每个符号序列的单词。

单词的实际定义是PCRE正则表达式引擎,其中单词是仅由单词字符组成的子字符串,由非单词字符分隔。

“单词”字符是任何字母、数字或下划线字符,也就是说,可以是Perl“单词”一部分的任何字符。这个字母和数字的定义由PCRE的字符控制表,如果正在进行特定于区域设置的匹配,则可能会有所不同(..)

Use:

$text = 'This is a test';
echo substr_count($text, 'is'); // 2

// So if you want to check if is exists in the text just put
// in a condition like this:
if (substr_count($text, 'is') > 0) {
    echo "is exists";
}