Skip to content
Advertisement

Insert spaces into a string at each change of character

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 the following recursive function, not knowing if this is the best way because I couldn’t find any build-in function in PHP for this.

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?

Advertisement

Answer

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';  
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement