考虑:

$a = 'How are you?';

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

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


当前回答

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";
}

其他回答

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

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

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

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

strpos函数工作得很好,但是如果您想对段落中的单词进行不区分大小写的检查,那么可以使用PHP的stripos函数。

例如

$result = stripos("I love PHP, I love PHP too!", "php");
if ($result === false) {
    // Word does not exist
}
else {
    // Word exists
}

查找字符串中不区分大小写的子字符串第一次出现的位置。

如果字符串中不存在该单词,则返回false,否则返回单词的位置。

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

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

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

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