php str_split() every n characters with accents

后端 未结 2 1736
盖世英雄少女心
盖世英雄少女心 2020-12-20 05:37

I\'ve this code to split a string every 3 characters, works fine, but accents are messed:

$splitted_array = str_split(\'waderòrò\',3);

but

相关标签:
2条回答
  • 2020-12-20 05:51

    I was having the same issue today and here is the solution that I am using. It is basicly using regular expressions.

    $re = '/\w{3}/u';
    $str = 'waderòròцчшщ中华人民共和国';
    
    preg_match_all($re, $str, $matches);
    
    // Print the entire match result
    print_r($matches);
    
    0 讨论(0)
  • 2020-12-20 06:02

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题