考虑:

$a = 'How are you?';

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

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


当前回答

特定字符串的另一种解决方案:

$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
    echo true;
}

也可以使用strpos()函数。

其他回答

Use:

$text = 'This is a test';
echo substr_count($text, 'is'); // 2

// So if you want to check if is exists in the text just put
// in a condition like this:
if (substr_count($text, 'is') > 0) {
    echo "is exists";
}

这里有一个小的实用函数,在这种情况下很有用

// returns true if $needle is a substring of $haystack
function contains($needle, $haystack)
{
    return strpos($haystack, $needle) !== false;
}

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

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

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

特定字符串的另一种解决方案:

$subject = 'How are you?';
$pattern = '/are/';
preg_match($pattern, $subject, $match);
if ($match[0] == 'are') {
    echo true;
}

也可以使用strpos()函数。

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