考虑:

$a = 'How are you?';

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

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


当前回答

许多使用subst_count的答案会检查结果是否大于0。但由于if语句将零视为false,因此可以避免该检查并直接写入:

if (substr_count($a, 'are')) {

若要检查是否不存在,请添加!操作员:

if (!substr_count($a, 'are')) {

其他回答

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

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

许多使用subst_count的答案会检查结果是否大于0。但由于if语句将零视为false,因此可以避免该检查并直接写入:

if (substr_count($a, 'are')) {

若要检查是否不存在,请添加!操作员:

if (!substr_count($a, 'are')) {

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

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

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

为了找到一个“单词”,而不是出现一系列实际上可能是另一个单词的一部分的字母,以下是一个很好的解决方案。

$string = 'How are you?';
$array = explode(" ", $string);

if (in_array('are', $array) ) {
    echo 'Found the word';
}

您还可以使用内置函数strchr()和strrchr()以及多字节字符串mb_strchr(()和mb_strrchr(()的扩展。这些函数返回部分字符串,如果找不到,则返回FALSE。

strchr()-查找字符串的第一次出现(是strstr()的别名)。strrchr()-查找字符串中最后出现的字符。