考虑:

$a = 'How are you?';

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

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


当前回答

Use:

$a = 'How are you?';
if (mb_strpos($a, 'are')) {
    echo 'true';
}

它执行多字节安全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,否则返回单词的位置。

可以使用以下函数检查字符串:

function either_String_existor_not($str, $character) {
    return strpos($str, $character) !== false;
}

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

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

您需要使用相同/不相同的运算符,因为strpos可以返回0作为其索引值。如果您喜欢三元运算符,请考虑使用以下运算符(我承认这有点倒退):

echo FALSE === strpos($a,'are') ? 'false': 'true';

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

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

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