Strpos 2 个变量[重复]

问题描述 投票:0回答:2

我想检查

$string
是否有2个字,我的条件应该有2个字而不是1个

我使用了以下代码,但只有当它至少有 1 个变量时它才有效

if ((strpos($string,'Good') || strpos($string,'Excellent')) === true) {
    $pid= '1';
} else { 
    $pid= '0'; 
} 

echo $pid;

有什么办法让它同时检查 2 个变量吗?

php strpos
2个回答
4
投票

重要的是要记住,

strpos()
返回字符串的索引,该索引可以为零,如果您没有正确检查,则其值为 false。当您想要检查两个条件是否都为真时,请始终严格比较,不要使用运算符。

if (strpos($string,'Good') !== false && strpos($string,'Excellent') !== false) {
    $pid= '1';
} else { 
    $pid= '0'; 
} 

或者,更简洁地使用三元

$pid = (strpos($string,'Good') !== false && strpos($string,'Excellent') !== false) ? 1 : 0;

为了扩展

strpos
的使用,请考虑这段代码,它返回“no”,因为“Good”位于第 0 个位置。

$string = "Good morning";
if (strpos($string, "Good")) {
    echo "yes";
} else {
    echo "no";
}

来自手册:

警告

此函数可能返回布尔值

FALSE
,但也可能返回计算结果为
FALSE
的非布尔值。请阅读Booleans部分以获取更多信息。使用 === 运算符 来测试该函数的返回值。


0
投票

你可以替换||使用 &&,尽管正则表达式可以帮助您变得更加具体,允许考虑大写字母和单词边界。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.