Count number of letters occurrence in string and output as human readable string e.g “aadbbbcddddd”
to “2ad3bc5d”
?
Did it in javascript syntax You can easily convert the syntax in php, not using RegEx
var str = 'aadbbbcddddkkkkkffffff'
var res = '';
var howMany = 1;
for (var i = 0; i < str.length; i++) {
if (str[i] == str[i+1]) {
howMany++;
} else {
res += (howMany > 1) ? howMany+str[i] : str[i];
howMany = 1;
}
}
console.log(res); //2ad3bc4d5k6f
You could use preg_replace_callback function.
$s = "aadbbbcddddd";
$out = preg_replace_callback(
'~(.)\1+~',
function($m) {
return strlen($m[0]).$m[1];
},
$s);
echo $out . "
";
Output:
2ad3bc5d
(.)
captures a character \1+
and the same captured character must be repeated one or more times. So this would match all the repeated characters and captures only the first character of repeated character.