考虑:

$a = 'How are you?';

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

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


当前回答

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

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

执行此操作并指定分隔符的一种方法是使用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的字符控制表,如果正在进行特定于区域设置的匹配,则可能会有所不同(..)

其他回答

如果搜索不区分大小写,则使用strstr()或stristr(。

许多使用subst_count的答案会检查结果是否大于0。但由于if语句将零视为false,因此可以避免该检查并直接写入:

if (substr_count($a, 'are')) {

若要检查是否不存在,请添加!操作员:

if (!substr_count($a, 'are')) {

您可以使用strstr函数:

$haystack = "I know programming";
$needle   = "know";
$flag = strstr($haystack, $needle);

if ($flag){

    echo "true";
}

不使用内置功能:

$haystack  = "hello world";
$needle = "llo";

$i = $j = 0;

while (isset($needle[$i])) {
    while (isset($haystack[$j]) && ($needle[$i] != $haystack[$j])) {
        $j++;
        $i = 0;
    }
    if (!isset($haystack[$j])) {
        break;
    }
    $i++;
    $j++;

}
if (!isset($needle[$i])) {
    echo "YES";
}
else{
    echo "NO ";
}

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

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。

短手版本

$result = false!==strpos($a, 'are');