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'; ?>