这不是错误,PREG_OFFSET_CAPTURE
是指字符串中字符的字节偏移量。
mb_ereg_search_pos
行为方式相同。一种可能性是之前将编码更改为 UTF-32,然后将位置除以 4(因为所有 unicode 代码单元在 UTF-32 中都表示为 4 字节序列):
mb_regex_encoding("UTF-32");
$string = mb_convert_encoding('hëllo', "UTF-32", "UTF-8");
$regex = mb_convert_encoding('[aäeëioöuáéíóú]', "UTF-32", "UTF-8");
mb_ereg_search_init ($string, $regex);
$positions = array();
while ($r = mb_ereg_search_pos()) {
$positions[] = reset($r)/4;
}
print_r($positions);
给出:
大批
(
[0] => 1
[1] => 4
)
您还可以将二进制位置转换为代码单元位置。对于 UTF-8,次优实现是:
function utf8_byte_offset_to_unit($string, $boff) {
$result = 0;
for ($i = 0; $i < $boff; ) {
$result++;
$byte = $string[$i];
$base2 = str_pad(
base_convert((string) ord($byte), 10, 2), 8, "0", STR_PAD_LEFT);
$p = strpos($base2, "0");
if ($p == 0) { $i++; }
elseif ($p <= 4) { $i += $p; }
else { return FALSE; }
}
return $result;
}