Strpos 2 变量

Strpos 2 variables

我想检查 $string 的 2 个词,我的条件应该有 2 个词而不仅仅是 1

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

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

echo $pid;

有没有让它同时检查 2 个变量的想法?

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

重要的是要记住 strpos() returns 字符串的索引,它可以为零,如果您没有正确检查,它的计算结果为 false。当你想检查 两个 条件是否为真时,请始终严格比较并且不要使用 运算符。

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

或者,更简洁地使用 ternary:

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

只是为了扩展 strpos 的使用,请考虑此代码,其中 returns “否”,因为“好”位于第零位。

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

来自手册:

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.