strpos 对某个字符串不起作用


strpos not working for a certain string

>我正在尝试使用 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"))被评估为假(因为在 PHP 中:0 == false为真)。为了确保找到指针(即使在索引 0 处),您需要使用严格的比较:

if (strpos("show me how to dance", "show me") !== false)

从 php 8.0 开始,您可以使用始终返回布尔值的str_contains

if ( str_contains("show me how to dance", "show me") )