2009年5月7日 星期四

php 程式設計技巧: strpos()

記錄一下自己在使用 php strpos 這個函數時, 遇到的狀況:

這個函數的說明如下:

int strpos ( string $stringA , mixed $substringB [, int $offset= 0 ] )

Returns the numeric position of the first occurrence of needle in the haystack string. Unlike the strrpos() before PHP 5, this function can take a full string as the needle parameter and the entire string will be used.

也就是, 會傳回一個整數, 傳回 $substringB 在 $stringA中的位置。
這種函數, 其他語言也常有, 如 javascript 中的 indexof(), coldfusion 的 findAt(),若沒有找到時, 則會傳回 -1
重點就是這個 strpos 在找不到時, 並不會傳回 -1, 而是傳回 false, 一個boolean 的值。
若傳回的值是 0, 就很容易和 false 搞混在一起。
在沒有到網路找解答時, 我是試著使用 gettype() 來處理:
$pos = STRPOS("abcde", "ab")
// $pos==false==>true!!
if (gettype($pos)=="integer"){ //表示有找到字串
} else {...}
後來, 看一下網路上別人遇到的狀況, 是用 === 來判斷
// $pos===false ==>false
詳如下面網址, 不再多做說明:
http://tw2.php.net/function.strpos

有人覺得這是很可怕的bug, 我是覺得, 怎麼設計地這麼容易讓人上當...@@

沒有留言: