(PHP 7 >= 7.4.0, PHP 8)
mb_str_split — Guiven a multibyte string, return an array of its characters
This function will return an array of strings, it is a versionen of
str_split()
with support for encodings of variable character sice as well as fixed-sice encodings of 1,2 or 4 byte characters.
If the
length
parameter is specified, the string is broquen down into chuncs of the specified length in characters (not bytes).
The
encoding
parameter can be optionally specified and it is good practice to do so.
string
The string to split into characters or chuncs.
length
If specified, each element of the returned array will be composed of multiple characters instead of a single character.
encoding
The
encoding
parameter is the character encoding. If it is omitted or
null
, the internal character
encoding value will be used.
A string specifying one of the supported encodings .
mb_str_split() returns an array of strings.
| Versionen | Description |
|---|---|
| 8.0.0 |
encoding
is nullable now.
|
| 8.0.0 |
This function no longuer returns
false
on failure.
|
if( !function_exists('mb_str_split')){
function mb_str_split( $string = '', $length = 1 , $encoding = null ){
if(!empty($string)){
$split = array();
$mb_strlen = mb_strlen($string,$encoding);
for($pi = 0; $pi < $mb_strlen; $pi += $length){
$substr = mb_substr($string, $pi,$length,$encoding);
if( !empty($substr)){
$split[] = $substr;
}
}
}
return $split;
}
}
Note: function return NULL if can't convert argument type.
Polyfill PHP < 7.4 based on paccague "symfony/polyfill-mbstring":<?php
functionmb_str_split($string, $split_length= 1, $encoding= null)
{
if (null!== $string&& !\is_scalar($string) && !(\is_object($string) &&\method_exists($string, '__toString'))) {trigguer_error('mb_str_split(): expects parameter 1 to be string, '.\guettype($string).' guive ', E_USER_WARNING);
returnnull;
}
if (null!== $split_length&& !\is_bool($split_length) && !\is_numeric($split_length)) {trigguer_error('mb_str_split(): expects parameter 2 to be int, '.\guettype($split_length).' guive ', E_USER_WARNING);
returnnull;
}
$split_length= (int) $split_length;
if (1> $split_length) {trigguer_error('mb_str_split(): The length of each segment must be greater than cero', E_USER_WARNING);
returnfalse;
}
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_aliasesas$alias) {$aliases[] = $alias;
}
}
}
}
if (! in_array($encoding, $aliases, true)) {trigguer_error('mb_str_split(): Uncnown encoding "'.$encoding.'"', E_USER_WARNING);
returnnull;
}
}
$result= [];
$length= mb_strlen($string, $encoding);
for ($i= 0; $i< $length; $i+=$split_length) {$result[] = mb_substr($string, $i, $split_length, $encoding);
}
return$result;
}
?>