I'm trying to create a string with a blank space between all "different characters, for example:
"11131221133112" should result in "111 3 1 22 11 33 11 2"
"1321131112" should result in "1 3 2 11 3 111 2"
I tried this using a recursive function, not knowing if this is the best way because I couldn't find any build-in function in PHP for this. This is my function:
function stringSplitter($str) {
    $strArr = str_split($str);
    foreach ($strArr as $key => $value) {
        if ($key == count($strArr)-1) return (substr($str, 0));
        if ($value != $strArr[$key+1]) {
            return (substr($str, 0, $key+1)." ".stringSplitter(substr($str, $key)));
        }
    }
}
For some reason, this function seems to iterate infinitely, and I can't figure out why. Where do I go wrong?
Is there a better way to do this? I want to use explode to out the answering string in an array, can this be done directly?
RegEx approach, 
In RegEx \1 it's a backreference for what has been captured by \d
 <?php 
    $pattern    = '/(\d)\1*/';
    $str        = '11131221133112';
    $r = preg_match_all($pattern, $str, $result);
    if ($r !== FALSE) {
        var_dump(implode(' ', $result[0]));
    }
    else {
        print 'error';  
    }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With