php下使用strpos需要注意 === 運算符
更新時間:2010年07月17日 23:54:42 作者:
首先應(yīng)該知道 strpos 函數(shù)可能返回布爾值 FALSE,但也可能返回一個與 FALSE 等值的非布爾值,例如 0 或者""。我們應(yīng)使用 === 運算符來測試本函數(shù)的返回值。
復(fù)制代碼 代碼如下:
<?php
/*
判斷字符串是否存在的函數(shù)
*/
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 第一次出現(xiàn)的位置為 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
// 在搜索字符的時候可以使用參數(shù) offset 來指定偏移量
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, not 0
?>
相關(guān)文章
深入eAccelerator與memcached的區(qū)別詳解
本篇文章是對eAccelerator與memcached的區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06php反射學(xué)習(xí)之不用new方法實例化類操作示例
這篇文章主要介紹了php反射學(xué)習(xí)之不用new方法實例化類操作,結(jié)合實例形式進(jìn)一步分析了php基于反射不用new方法進(jìn)行實例化類的相關(guān)操作技巧,需要的朋友可以參考下2019-06-06