考虑:

$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的字符控制表,如果正在进行特定于区域设置的匹配,则可能会有所不同(..)

其他回答

虽然这些答案中的大多数都会告诉你字符串中是否出现了子字符串,但如果你要查找的是一个特定的单词,而不是子字符串,那么这通常不是你想要的。

有什么不同?子字符串可以出现在其他单词中:

“area”开头的“are”“野兔”末尾的“are”“are”位于“fare”的中间

缓解这种情况的一种方法是使用正则表达式和单词边界(\b):

function containsWord($str, $word)
{
    return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}

这种方法没有上面提到的假阳性,但它有自己的一些边缘情况。单词边界与非单词字符(\W)匹配,这些字符将是非a-z、a-z、0-9或_的任何字符。这意味着数字和下划线将被计算为单词字符,类似这样的场景将失败:

“你在想什么?”中的“是”“哦,你不知道那些是4吗?”

如果你想要比这更准确的东西,你必须开始进行英语语法分析,这是一个相当大的蠕虫(而且假设语法使用正确,但这并不总是给定的)。

您需要使用相同/不相同的运算符,因为strpos可以返回0作为其索引值。如果您喜欢三元运算符,请考虑使用以下运算符(我承认这有点倒退):

echo FALSE === strpos($a,'are') ? 'false': 'true';

更简单的选择:

return ( ! empty($a) && strpos($a, 'are'))? true : false;

strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。

例如

$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
    // Word does not exist
}
else {
    // Word exists
}

查找字符串中不区分大小写的子字符串第一次出现的位置。

如果字符串中不存在该单词,则返回false,否则返回单词的位置。

查看strpos():

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'.";
} else {
    echo "The string '$findme' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}