为什么 $str1 不包含 $str2? (PHP strpos)

Why does $str1 not contain $str2? (PHP strpos)

代码:

<?php
$str1 = "subidubidu";
$str2 = "subi";

if(strpos($str1,$str2)){
echo "Contains!";
}else{
echo "Not contains!";
} 
?> 

结果是"Not contains",我很好奇为什么? 可能是问题所在,"subi" 位于 [0] 的索引处,而 0 returns 为 false?有什么想法吗?

<?php

$str1 = "subidubidu";
$str2 = "subi";

if (strpos($str1, $str2)!==false) {
    echo "Contains!";
} else {
    echo "Not contains!";
}

您正在寻找这个 --- strpos returns position if found and false if not

希望对你有帮助

$str1 = "subidubidu";
$str2 = "subi";    

if (strpos($str1, $str2) !== FALSE)
    {
     echo 'Found it';
    }
    else
    {
     echo 'Not found.';
    }

如果你看一下 documentation:

Note our use of ===. Simply == would not work as expected because the position of 'a' was the 0th (first) character.

它声明您不能只使用 == 比较,这是您在键入

时所做的
if (strpost($str1, $str2)) { .. }

您需要使用===。所以它看起来像:

<?php

$str1 = "subidubidu";
$str2 = "subi";

if (strpos($str1, $str2)!==false) {
    echo "Contains!";
} else {
    echo "Not contains!";
}

你的代码是正确的。但是问题就在这里:

解释:

strpos函数return包含字符串的索引。在您的情况下,它是 returning 0 作为字符串的索引。而 0 在编程中表示 false。这就是为什么您的代码执行其他部分的原因。

以防万一,如果您的字符串位于 1 或 2 等位置,则代码可以正常工作。但这将是错误的,因为匹配字符串位于第 0 个位置。

为了将来的前景,您必须将值放入这样的变量中:

$str1 = "subidubidu";
$str2 = "subi";    
$pos = strpos($str1, $str2);

if ($pos != '' || $pos !== false) {
   echo 'Found it';
} else {
   echo 'Not found.';
}