It appears that the $offset value is a character count not a byte count. (This may seem obvious but it isn't explicitly stated)
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
mb_strpos — 查找字符串在另一个字符串中首次出现的位置
返回 string 的 haystack
中 needle
首次出现位置的数值。
如果没有找到 needle
,它将返回 false
。
版本 | 说明 |
---|---|
8.0.0 |
现在 needle 接受空字符串。
|
8.0.0 |
现在 encoding 可以为 null。
|
7.1.0 |
支持负数的 offset 。
|
It appears that the $offset value is a character count not a byte count. (This may seem obvious but it isn't explicitly stated)
a sample mb_str_replace function:
function mb_str_replace($haystack, $search,$replace, $offset=0,$encoding='auto'){
$len_sch=mb_strlen($search,$encoding);
$len_rep=mb_strlen($replace,$encoding);
while (($offset=mb_strpos($haystack,$search,$offset,$encoding))!==false){
$haystack=mb_substr($haystack,0,$offset,$encoding)
.$replace
.mb_substr($haystack,$offset+$len_sch,1000,$encoding);
$offset=$offset+$len_rep;
if ($offset>mb_strlen($haystack,$encoding))break;
}
return $haystack;
}
sorry, my previous post had an error. replace the 1000 with strlen($haystack) to handle strings longer than 1000 chars.
btw. This is an issue with the mbstring functions. you can't specify the $encoding without specifying a $length, thus this reduces the functionality of mb_substr compared to substr