首页 > 资讯列表 > 编程/数据库 >> PHP

php下使用strpos需要注意 === 运算符

PHP 2014-12-07 17:21:06 转载来源: 网络整理/侵权必删

本文为大家讲解的是php下使用strpos需要注意 === 运算符,感兴趣的同学参考下。 首先应该知道 strpos 函数可能返回布尔值 FALSE,但也可能返回一个与 FALSE 等值的非布尔值,例如 0 或者""

本文为大家讲解的是php使用strpos需要注意 === 运算符,感兴趣的同学参考下。

首先应该知道 strpos 函数可能返回布尔值 FALSE,但也可能返回一个与 FALSE 等值的非布尔值,例如 0 或者""。我们应使用 === 运算符来测试本函数的返回值。


<?php
/*
判断字符串是否存在的函数
*/
function strexists($haystack, $needle) {
return !(strpos($haystack, $needle) === FALSE);//注意这里的"==="
}
/*
Test
*/
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);

// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
// 简单的使用 "==" 号是不会起作用的,需要使用 "===",因为 a 第一次出现的位置为 0
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}

// We can search for the character, ignoring anything before the offset
// 在搜索字符的时候可以使用参数 offset 来指定偏移量
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>

标签: php 使用 strpos 需要 注意 运算符


声明:本文内容来源自网络,文字、图片等素材版权属于原作者,平台转载素材出于传递更多信息,文章内容仅供参考与学习,切勿作为商业目的使用。如果侵害了您的合法权益,请您及时与我们联系,我们会在第一时间进行处理!我们尊重版权,也致力于保护版权,站搜网感谢您的分享!

站长搜索

http://www.adminso.com

Copyright @ 2007~2024 All Rights Reserved.

Powered By 站长搜索

打开手机扫描上面的二维码打开手机版


使用手机软件扫描微信二维码

关注我们可获取更多热点资讯

站长搜索目录系统技术支持