Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active January 18, 2024 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stemar/e568e594328af40d26f31d17c159a664 to your computer and use it in GitHub Desktop.
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
<?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