考虑:

$a = 'How are you?';

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

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


当前回答

短手版本

$result = false!==strpos($a, 'are');

其他回答

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

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

我有点印象深刻,这里没有一个使用strpos、strstr和类似函数的答案提到多字节字符串函数(2015-05-08)。

基本上,如果您在查找某些语言(如德语、法语、葡萄牙语、西班牙语等)特定字符的单词时遇到困难(例如:ä,é,ô,ç,º,ñ),您可能需要在函数前面加上mb_。因此,接受的答案将使用mb_strpos或mb_stripos(用于不区分大小写的匹配):

if (mb_strpos($a,'are') !== false) {
    echo 'true';
}

如果不能保证所有数据都是100%的UTF-8格式,则可能需要使用mb_函数。

乔尔·斯波尔斯基(Joel Spolsky)的一篇很好的文章解释了为什么每个软件开发人员都必须了解Unicode和字符集(没有借口!)。

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

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

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

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

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