SA__ SA__ - 5 months ago 10
PHP Question

String compression in php

Here is my input

aaaabbaaaababbbcccccccccccc


And this is my expected output

a4b2a4b1a1b3c12


I tried like doing
foreach
and then
concating
the count of values. It seems like brutforcing. Is there any way to do it efficiently in php .

Help pls

Answer

You can use regular expression to get the result

preg_match_all('/(.)\1*/', $str, $m, PREG_SET_ORDER);
$m = array_map(function($i) { return $i[1] . strlen($i[0]); } , $m);
echo implode('', $m);   // a4b2a4b1a1b3c12

demo