php - php strpos()无法在字符串中找到括号
问题描述
当我使用 strpos() 时,如果该括号是字符串中的第一个字符,则无法找到“[”。我该如何克服这个问题,为什么会这样?
$name = "[johnny";
if(strpos($name, "[") != false){
echo "Bracket found!";}else{
echo "Not found";
}
在上面的代码中,当它不应该出现时,我得到“未找到”。
$name = "jo[hnny";
if(strpos($name, "[") != false){
echo "Bracket found!";}else{
echo "Not found";
}
但这种情况下正确返回“发现括号!”
解决方案
您必须使用!== false
(双等号)
此函数可能返回布尔值 false,但也可能返回计算结果为 false 的非布尔值。请阅读有关布尔值的部分以获取更多信息。使用 === 运算符测试此函数的返回值。
以及页面上给出的示例:
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// The !== operator can also be used. Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
推荐阅读
- c# - 如何防止自定义过滤器两次调用?
- javascript - React 钩子中功能组件内部的功能 - 性能
- mysql - MySQL 子查询 - 在 WHERE 条件下使用 SELECT 的别名(无 CTE)
- webpack - Gulp 任务抛出“你忘记发出异步完成信号了吗?” 由于不同的 webpack-stream 设置
- eclipse - why I am getting an error while launching eclipse in headless mode for building rule app using automation tool plugin
- android - android exoplayer 未正确安装且未跨设备拉伸
- sql-server - 限制 Windows 身份验证以访问 SQL Server 数据库
- .htaccess - 为标签重定向 301 不起作用。怎么弄?
- java - 如何在 Unirest 中将响应正文作为 InputStream 接收?
- tabulator - 为每个单元格制作自定义工具提示