考虑:

$a = 'How are you?';

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

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


当前回答

我认为一个好主意是使用mb_stpos:

$haystack = 'How are you?';
$needle = 'are';

if (mb_strpos($haystack, $needle) !== false) {

    echo 'true';
}

因为此解决方案区分大小写,并且对所有Unicode字符都是安全的。


但你也可以这样做(sauch的回应还没有):

if (count(explode($needle, $haystack)) > 1) {

    echo 'true';
}

此解决方案对Unicode字符也区分大小写并安全。

此外,在表达式中不使用否定,这会增加代码的可读性。


以下是使用函数的其他解决方案:

function isContainsStr($haystack, $needle) {

    return count(explode($needle, $haystack)) > 1;
}

if (isContainsStr($haystack, $needle)) {

    echo 'true';
}

其他回答

查看strpos():

<?php
$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===. Simply, == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
    echo "The string '$findme' was not found in the string '$mystring'.";
} else {
    echo "The string '$findme' was found in the string '$mystring',";
    echo " and exists at position $pos.";
}
if (preg_match('/(are)/', $a)) {
   echo 'true';
}

我认为一个好主意是使用mb_stpos:

$haystack = 'How are you?';
$needle = 'are';

if (mb_strpos($haystack, $needle) !== false) {

    echo 'true';
}

因为此解决方案区分大小写,并且对所有Unicode字符都是安全的。


但你也可以这样做(sauch的回应还没有):

if (count(explode($needle, $haystack)) > 1) {

    echo 'true';
}

此解决方案对Unicode字符也区分大小写并安全。

此外,在表达式中不使用否定,这会增加代码的可读性。


以下是使用函数的其他解决方案:

function isContainsStr($haystack, $needle) {

    return count(explode($needle, $haystack)) > 1;
}

if (isContainsStr($haystack, $needle)) {

    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和字符集(没有借口!)。

Use:

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

它执行多字节安全strpos()操作。