我想使用strpos函数在一个字符串中查找另一个字符串,但是对于某个特定的字符串却无法正常工作,尽管它对于其他字符串可以正常工作。我做错了什么?
<?php
if (strpos("show me how to dance", "show me")) {
echo "true1";
}
if (strpos("my name is name", "name")) {
echo "true2";
}
?>
结果:
true2
期望结果:
true1true2
strpos
函数返回字符串中指定内容的位置索引(如果未找到则返回 false)。当该位置索引为 0 时,条件 (strpos("show me how to dance", "show me"))
会被判断为 false(因为在 PHP 中,0 == false
是 true)。为了确保即使在索引为 0 的情况下也能找到指定内容,需要使用严格比较。请注意,不要删除原有的 HTML 标签。if (strpos("show me how to dance", "show me") !== false)
str_contains
函数来获得布尔值:if ( str_contains("show me how to dance", "show me") )
strpos
是最好的方式,preg_match
可能有点过头了(除非你想检查单词边界)。 - Casimir et Hippolyte
true2
。因为位置0
的值被解释为false
。 - AbraCadaver