Last active
February 10, 2025 15:47
-
-
Save stemar/e568e594328af40d26f31d17c159a664 to your computer and use it in GitHub Desktop.
Multibyte str_split(). The mbstring library PHP < 7.x doesn’t come with a multibyte equivalent of str_split(). This function behaves like mb_str_split in PHP >= 7.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mb_str_split($string, $length = 1, $encoding = NULL) { | |
if (!is_null($string) && !is_scalar($string)) { | |
$type = gettype($string) === 'object' ? get_class($string) : gettype($string); | |
throw new \Exception(sprintf('mb_str_split(): Argument #1 ($string) must be of type string, %s given', $type)); | |
} | |
if ((!is_null($length) && !is_numeric($length)) || $length === '') { | |
$type = gettype($length) === 'object' ? get_class($length) : gettype($length); | |
throw new \Exception(sprintf('mb_str_split(): Argument #2 ($string) must be of type int, %s given', $type)); | |
} | |
if ((int)$length < 1) { | |
throw new \Exception('mb_str_split(): Argument #2 ($length) must be greater than 0'); | |
} | |
if ($encoding === NULL) { | |
$encoding = mb_internal_encoding(); | |
} | |
$array = array(); | |
$n = mb_strlen($string, $encoding); | |
for ($i = 0; $i < $n; $i += $length) { | |
$array []= mb_substr($string, $i, $length, $encoding); | |
} | |
// PHP v5 str_split behaviour | |
// if (!$array) { | |
// return array(''); | |
// } | |
return $array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment