Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string at 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 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?

like image 672
BluePrint Avatar asked Dec 10 '15 10:12

BluePrint


1 Answers

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';  
    }
like image 84
Halayem Anis Avatar answered Oct 02 '22 02:10

Halayem Anis