考虑:

$a = 'How are you?';

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

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


当前回答

如果只想检查一个字符串是否包含在另一个字符串中,请不要使用preg_match()。改用strpos()或strstr(),因为它们会更快。(http://in2.php.net/preg_match)

if (strpos($text, 'string_name') !== false){
   echo 'get the string';
}

其他回答

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

使用stripos()使用不区分大小写的匹配:

if (stripos($string,$stringToSearch) !== false) {
    echo 'true';
}

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

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

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

要确定一个字符串是否包含另一个字符串,可以使用PHP函数strpos()。

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )`
<?php

$haystack = 'how are you';
$needle = 'are';

if (strpos($haystack,$needle) !== false) {
    echo "$haystack contains $needle";
}

?>

警告:

如果您正在搜索的针位于干草堆的开始位置,它将返回位置0,如果您进行==比较,但这不起作用,则需要执行===

A==符号是一个比较,用于测试左侧的变量/表达式/常量是否与右侧的变量/表达/常量具有相同的值。

A==符号是比较两个变量/表达式/常量是否相等并且具有相同的类型,即两者都是字符串或两者都是整数。

使用这种方法的优点之一是,与str_contains()不同,每个PHP版本都支持此函数。

查看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.";
}