支持中文字符串
一个合适的unicode字符串分割函数
/**
* 将unicode字符串按传入长度分割成数组
* @param string $str 传入字符串
* @param integer $l 字符串长度
* @return mixed 数组或false
*/
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
例子:
<?php
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
?>
$s = "Il?k süt"; // Mild milk
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
Array
(
[0] => Il?
[1] => ?k
[2] => sü
[3] => t
)
Array
(
[0] => Il?
[1] => k s
[2] => üt
)