考虑:

$a = 'How are you?';

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

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


当前回答

如果要避免“虚假”和“真实”问题,可以使用subst_count:

if (substr_count($a, 'are') > 0) {
    echo "at least one 'are' is present!";
}

它比strpos慢一点,但它避免了比较问题。

其他回答

可以通过三种不同的方式完成:

 $a = 'How are you?';

1-stristr()

 if (strlen(stristr($a,"are"))>0) {
    echo "true"; // are Found
 } 

2-strpos()

 if (strpos($a, "are") !== false) {
   echo "true"; // are Found
 }

3-preg_match()

 if( preg_match("are",$a) === 1) {
   echo "true"; // are Found
 }

要确定一个字符串是否包含另一个字符串,可以使用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.";
}
if (preg_match('/(are)/', $a)) {
   echo 'true';
}

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