Jo Fransiz Jo Fransiz - 1 year ago 84
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:

$string = "tohothin";

After regex:

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

Answer Source

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);
$result = implode('', $letters);

Yields: bccemruu

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download