note 117112 deleted from function.str-split by crell
| From: | crell@php.net | Date: | Wed, 29 Jun 2022 18:29:18 +0000 |
| Subject: | note 117112 deleted from function.str-split by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218684@lists.php.net to get a copy of this message | ||
Note Submitter: veszelovszki at gmail dot com
----
Here is a better version of queremy@gmail.com's solution. It has the exact same interface as
str_split, but works with any UTF-8 string.
<?php
if (!function_exists('mb_str_split')) {
/**
* Converts an UTF-8 string to an array.
*
* E.g. mb_str_split("Hello Friend");
* returns ['H', 'e', 'l', 'l', 'o', '
', 'w', 'o', 'r', 'l', 'd']
*
* @param string $string The input string.
* @param int $split_length Maximum length of the chunk. If specified, the returned array will
be broken down
* into chunks with each being split_length in length, otherwise each chunk will be one
character in length.
* @return array|boolean
* -
* - If the split_length length exceeds the length of string, the entire string is
returned
* as the first (and only) array element.
* - False is returned if split_length is less than 1.
*/
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;
}
}
}
?>