strpos — 查找字符串首次出現的位置(區分大小寫)
返回值:返回在 字符串 haystack
中 needle
首次出現的數字位置。
同時注意字符串位置起始於 0,而不是 1。
如果未發現 needle 將返回 FALSE
。 此函數可能返回布爾值 FALSE
,但也可能返回等同於 FALSE
的非布爾值。應使用 === 運算符來測試此函數的返回值。
參數: haystack -在該字符串中查找。
needle- 注意
needle
可以是一個單字符或者多字符的字符串。如果 needle
不是一個字符串,那么它將被轉換為整型並被視為字符順序值。
可選的 offset-
offset
參數允許你指定從 haystack
中的哪個字符開始查找。返回的位置數字值仍然相對於 haystack
的起始位置。
$srt = 'howare you'; echo strpos($srt, 'o'); //1 echo strpos($srt, 'o', 2); //8
$str = 'howare you'; $newstr=strpos($str,'h'); var_dump($newstr); //0 if ($newstr===false){ //因 是從 0開始找,返回 0 則 if($newstr) == false echo '未找到'; }else{ echo '找到'; }
stripos() - 查找字符串首次出現的位置(不區分大小寫)
利用 strpos 寫一個函數 統計字符串中字符出現的次數
<?php header("Content-Type: text/html;charset=utf-8"); // 思路: // 先從頭查找子串,找到后,則偏移過去子串,繼續查找。直到查不到. function subnum($str, $sub) { $sublen = strlen($sub); //計算出子串的長度 $strlen = strlen($str); //計算出父串的長度 if ($sublen > $strlen) { return 0; } //如果子串比父串長,沒必要找了 // for ($offset = 0, $num = 0; ($offset = strpos($str, $sub, $offset)) !== false;) { // $num += 1; // $offset += $sublen; // } for ($offset = 0, $num = 0; ($offset = strpos($str, $sub, $offset)) !== false; $num += 1, $offset += $sublen) { } return $num; } $str = 'how are you? fine thank you,fine, may be you are right, 256,I dont think so,let me see,I can not fine'; echo "找到", subnum($str, 'fine'), '個find'; ?>