PHP 问题 : strpos function not working

标签 php substr

为什么下面的 php 代码不起作用:

$string = "123";
$search = "123";

if(strpos($string,$search))
{
    echo "found";
}else{
    echo "not found";
}

因为 $search 在 $string 中 - 它不应该在找到时触发吗?

最佳答案

Manual: strpos() 中提到了这一点

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

在你的例子中,字符串在索引 0 和 php 0 == false 中找到

解决方案是只使用严格比较器

echo strpos($string,$search) === false
     ? "not found"
     : "found";

另一个

echo is_int(strpos($string,$search))
     ? "found"
     : "not found";

或者某事...让我们说有趣 :D 仅供说明。我不推荐这个。

echo strpos('_' . $string,$search) // we just shift the string 1 to the right
     ? "found"
     : "not found";

关于PHP 问题 : strpos function not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099309/

相关文章:

php - Codeigniter - 获取所有用户 session 数据

php - 插入表 - 用数组替换列名和值

php - 如何包含来自破坏元素的文本?

php - Nginx clean urls,如何将文件夹重写为 try_files 的参数

php - 在配置文件中使用闭包作为数组值

perl - 我可以使用 Perl 的 unpack 将字符串分解为 var 吗?

r - 从 r 中的字符列中提取最后 n 个字符

MYSQL DELETE 查询中的行与 substr

c++ - 无法使用 C++ 在同一个字符串上多次使用 string.substr(x, y)?