I would process the string per character. Create 'a chunk', if character is same as previous add it to the chunk. If remaining of input string is shorter than the wanted chunk length, add it to the last created chunk. But what needs to be done if the input string is not perfectly 'in pairs of numbers'?
/**
* @return string[]
*/
function toChunks(string $input, int $chunkLength = 2): array
{
$result = array();
$inputLength = strlen($input);
$chunk = '';
$currentChar = '';
$prevChar = '';
for ($i = 0; $i < $inputLength; $i++) {
$prevChar = $currentChar;
$currentChar = $input[$i];
if (strlen($chunk) === $chunkLength) {
$result[] = $chunk;
$chunk = '';
}
if (($inputLength - $i) < $chunkLength) {
if($chunk === ''){
$result[sizeof($result) - 1] .= substr($input, $i); // add remainder to last created chunck
}else{
$result[] = $chunk . substr($input, $i); // add remainder to current chunk and then to the result
}
break;
}
if (strlen($chunk) < $chunkLength && ($currentChar === $prevChar || strlen($chunk) === 0)) {
$chunk .= $currentChar;
}
// else, $currentChar != $prevChar, what should be done?
}
return $result;
}
echo '<br><br>';
echo 'toChunks()';
echo '<br>';
foreach(array('112233', '1122333', '11223333', '1122233') as $string){
echo 'Input: '.$string;
echo '<br>';
echo 'Output: '.print_r(toChunks($string), true);
echo '<br><br>';
}
Produces:
toChunks()
Input: 112233
Output: Array ( [0] => 11 [1] => 22 [2] => 33 )
Input: 1122333
Output: Array ( [0] => 11 [1] => 22 [2] => 333 )
Input: 11223333
Output: Array ( [0] => 11 [1] => 22 [2] => 33 [3] => 33 )
Input: 1122233
Output: Array ( [0] => 11 [1] => 22 [2] => 23 ) // this is not covered :*)