mb_str_split

(PHP 7 >= 7.4.0, PHP 8)

mb_str_splitマルチバイト文字列を受取り、文字の配列を返す

説明

mb_str_split(string $string, int $length = 1, ?string $encoding = null): array

この関数は文字列の配列を返します。 これは str_split() に 1, 2 または 4バイトの固定長のエンコーディングだけでなく、 可変長のエンコーディングのサポートも追加したものです。 length を指定すると、 文字列は指定された数の(バイトではなく)文字のチャンクに分割されます。 encoding もオプションで指定できますが、 指定するほうが良いでしょう。

パラメータ

string

文字またはチャンクに分割する string

length

これを指定すると、返される配列の個々の要素は一文字ではなく複数の文字になります。

encoding

encoding パラメータには文字エンコーディングを指定します。省略した場合、もしくは null の場合は、 内部文字エンコーディングを使用します。

サポートされているエンコーディングのうち、ひとつを指定した文字列

戻り値

mb_str_split() は、string の配列を返します。

変更履歴

バージョン 説明
8.0.0 encoding は、nullable になりました。
8.0.0 この関数は、失敗時に false を返さなくなりました。

参考

add a note add a note

User Contributed Notes 2 notes

up
4
info at ensostudio dot ru
3 years ago
Note: function return NULL if can't convert argument type.

Polyfill PHP < 7.4 based on package "symfony/polyfill-mbstring":
<?php
function mb_str_split($string, $split_length = 1, $encoding = null)
{
    if (
null !== $string && !\is_scalar($string) && !(\is_object($string) && \method_exists($string, '__toString'))) {
       
trigger_error('mb_str_split(): expects parameter 1 to be string, '.\gettype($string).' given', E_USER_WARNING);
        return
null;
    }
    if (
null !== $split_length && !\is_bool($split_length) && !\is_numeric($split_length)) {
       
trigger_error('mb_str_split(): expects parameter 2 to be int, '.\gettype($split_length).' given', E_USER_WARNING);
        return
null;
    }
   
$split_length = (int) $split_length;
    if (
1 > $split_length) {
       
trigger_error('mb_str_split(): The length of each segment must be greater than zero', E_USER_WARNING);
        return
false;
    }
    if (
null === $encoding) {
       
$encoding = mb_internal_encoding();
    } else {
       
$encoding = (string) $encoding;
    }
   
    if (!
in_array($encoding, mb_list_encodings(), true)) {
        static
$aliases;
        if (
$aliases === null) {
           
$aliases = [];
            foreach (
mb_list_encodings() as $encoding) {
               
$encoding_aliases = mb_encoding_aliases($encoding);
                if (
$encoding_aliases) {
                    foreach (
$encoding_aliases as $alias) {
                       
$aliases[] = $alias;
                    }
                }
            }
        }
        if (!
in_array($encoding, $aliases, true)) {
           
trigger_error('mb_str_split(): Unknown encoding "'.$encoding.'"', E_USER_WARNING);
            return
null;
        }
    }
   
   
$result = [];
   
$length = mb_strlen($string, $encoding);
    for (
$i = 0; $i < $length; $i += $split_length) {
       
$result[] = mb_substr($string, $i, $split_length, $encoding);
    }
    return
$result;
}
?>
up
-1
vovan-ve at yandex dot ru
3 years ago
Lazy polyfill for UTF-8 only:

function utf8_str_split(string $input, int $splitLength = 1)
{
    $re = \sprintf('/\\G.{1,%d}+/us', $splitLength);
    \preg_match_all($re, $input, $m);
    return $m[0];
}
To Top