Home » Php » php – Split string at change of character

php – Split string at change of character

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

RegEx approach,
In RegEx \1 it’s a backreference for what has been captured by \d

 <?php 
    $pattern    = '/(\d)*/';
    $str        = '11131221133112';

    $r = preg_match_all($pattern, $str, $result);
    if ($r !== FALSE) {
        var_dump(implode(' ', $result[0]));
    }
    else {
        print 'error';  
    }

Answer:

simplest solution is:

$string = '11131221133112';
$strarr = str_split($string);
$tmp = null;
$newstr = '';
foreach($strarr as $a){
    $newstr .= ($a == $tmp) ? $a:' '.$a;
    $tmp = $a;
}

echo $newstr;

output: 111 3 1 22 11 33 11 2

Answer:

Nice question 🙂

You can loop over your characters and keep an eye on the last one, if it is different from the current character add a space to output, then add the character itself.

<?php
$string="11131221133112";
$last="";

for($i=0;$i<strlen($string);$i++)
{
   $output.= $string[$i]!=$last ? " ".$string[$i] :  $string[$i];
   $last=$string[$i];
}
$output=trim($output);

Output

111 3 1 22 11 33 11 2

And

1 3 2 11 3 111 2

Fiddle

Answer:

Try this.

$string="11131221133112";
$seperated=str_split($string);
$lastChar='';
foreach ($seperated as $key => $value) {
    if($lastChar!=''&&$lastChar!=$value){
            echo ' ';
    }
    $lastChar=$value;
    echo $value;
}