Jo Fransiz Jo Fransiz - 17 days ago 7
PHP Question

Convert string to grouped by letters

How I can create regex that converts a string to another string which is grouped by letters or numbers:

$string = "cucumber";


After regex:
ccuumber


$string = "tohothin";


After regex:
ttoohhin


How I can create this with PHP? It is not important with regex, it may be another function.

Answer

Well, I didn't see an attempt, but I was bored:

$result = '';

foreach(array_count_values(str_split($string)) as $letter => $count) {
    $result .= str_repeat($letter, $count);
}

Yields: ccuumber

Sorting will work, but give a different order:

$letters = str_split($string);
sort($letters);
$result = implode('', $letters);

Yields: bccemruu

Comments