考虑:

$a = 'How are you?';

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

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


当前回答

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

 $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
 }

其他回答

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

 $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
 }

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

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

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

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

if (preg_match('/(are)/', $a)) {
   echo 'true';
}

我认为一个好主意是使用mb_stpos:

$haystack = 'How are you?';
$needle = 'are';

if (mb_strpos($haystack, $needle) !== false) {

    echo 'true';
}

因为此解决方案区分大小写,并且对所有Unicode字符都是安全的。


但你也可以这样做(sauch的回应还没有):

if (count(explode($needle, $haystack)) > 1) {

    echo 'true';
}

此解决方案对Unicode字符也区分大小写并安全。

此外,在表达式中不使用否定,这会增加代码的可读性。


以下是使用函数的其他解决方案:

function isContainsStr($haystack, $needle) {

    return count(explode($needle, $haystack)) > 1;
}

if (isContainsStr($haystack, $needle)) {

    echo 'true';
}