Function str_split in PHP4


According to the document of PHP official website, http://php.net/manual/en/function.str-split.php

str_split
(PHP 5) str_split — Convert a string to an array


So, it’s only for PHP5+. In PHP4, we use this function below:

<?
if (!function_exists('str_split')) {
    function str_split($text, $split = 1)
    {
        if (!is_string($text))
            return false;
        if (!is_numeric($split) && $split < 1)
            return false;

        $len = strlen($text);
        $array = array();
        $i = 0;

        while ($i < $len) {
            $key = null;
            for ($j = 0; $j < $split; $j += 1) {
                $key .= $text{$i};
                $i += 1;
            }
            $array[] = $key;
        }
        return $array;
    }
}
?>

or these functions below:

<?
if (!function_exists('str_split')) {
    function str_split($string, $chunksize = 1)
    {
        preg_match_all('/(' . str_repeat('.', $chunksize) . ')/Us', $string, $matches);
        return $matches[1];
    }
}
?>
<?php
if (!function_exists('str_split')) {
    function str_split($string, $length = 1)
    {
        if (strlen($string) > $length || !$length) {
            do {
                $c = strlen($string);
                $parts[] = substr($string, 0, $length);
                $string = substr($string, $length);
            } while ($string !== false);
        } else {
            $parts = array($string);
        }
        return $parts;
    }
}
?>

Leave a Reply