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

2015-01-24信息快讯网

首先应该知道 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使用示例
使用JSON实现数据的跨域传输的php代码
如何使用Linux的Crontab定时执行PHP脚本的方法
PHP substr 截取字符串出现乱码问题解决方法[utf8与gb2312]
php中使用DOM类读取XML文件的实现代码
php使用Smarty的相关注意事项及访问变量的几种方式
PHP spl_autoload_register实现自动加载研究
PHPWind与Discuz截取字符函数substrs与cutstr性能比较
PHP循环语句笔记(foreach,list)
使用php+Ajax实现唯一校验实现代码[简单应用]
PHP中strtotime函数使用方法详解
php中$_REQUEST、$_POST、$_GET的区别和联系小结
PHP中文处理 中文字符串截取(mb_substr)和获取中文字符串字数
PHP中的strtr函数使用介绍(str_replace)
php中模拟POST传递数据的两种方法分享
php中使用Curl、socket、file_get_contents三种方法POST提交数据
ajax 的post方法实例(带循环)
php设计模式 Composite (组合模式)
php 无限级数据JSON格式及JS解析
按上下级层次关系输出内容的PHP代码
Windows下XDebug 手工配置与使用说明
PHP 数组遍历方法大全(foreach,list,each)
《Head First 设计模式》代码之PHP版(面向对象学习)第1/2页
PHP print类函数使用总结
php $_SERVER["REQUEST_URI"]获取值的通用解决方法
joomla内置的表单验证功能使用方法
php中static静态变量的使用方法详解
php Static关键字实用方法
PHP stristr() 函数(不区分大小写的字符串查找)
php strstr查找字符串中是否包含某些字符的查找函数
PHP 工厂模式使用方法
php 使用post,get的一种简洁方式
PHP CURL模拟GET及POST函数代码
php strcmp使用说明
一个PHP的String类代码
PHP strtok()函数的优点分析
©2014-2024 dbsqp.com