字符串按长度分割成数组函数
程序员文章站
2022-05-08 23:26:43
...
支持中文字符串
一个合适的unicode字符串分割函数
一个合适的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
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
例子:
function str_split_unicode($str, $l = 0) {
if ($l > 0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i
$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
)
AD:真正免费,域名+虚机+企业邮箱=0元