问题描述
我有这段代码可以每3个字符分割一个字符串,效果很好,但是口音很混乱:
I've this code to split a string every 3 characters, works fine, but accents are messed:
$splitted_array = str_split('waderòrò',3);
但它输出
print_r($splitted_array ); >> Array ( [0] => wad [1] => er▯ [2] => ▯r▯ [3] => ▯ )
我知道已经问过类似的问题,但是这个问题并没有帮助我. ucwords和法语重音字母编码.我确实尝试了mb_split,但没有成功,因为我找不到正确的正则表达式...正确的代码是什么?
I know similar question was already asked, but this question didn't help me. ucwords and french accented lettres encoding. I did try mb_split, but without success, because I wasn't able to find the right regex... What would be the right code?
推荐答案
用户"veszelovszki at gmail dot com"在PHP str_split手册页上发布了以下解决方案.这是str_split()函数的多字节安全变体.
User "veszelovszki at gmail dot com" posted the below solution to the PHP str_split manual page. It is a multibyte-safe variation of the str_split() function.
function mb_str_split($string, $split_length = 1)
{
if ($split_length == 1) {
return preg_split("//u", $string, -1, PREG_SPLIT_NO_EMPTY);
} elseif ($split_length > 1) {
$return_value = [];
$string_length = mb_strlen($string, "UTF-8");
for ($i = 0; $i < $string_length; $i += $split_length) {
$return_value[] = mb_substr($string, $i, $split_length, "UTF-8");
}
return $return_value;
} else {
return false;
}
}
这篇关于php str_split()每n个带有重音符号的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!