将字符串转换为按字母分组(Convert string to grouped by letters)

如何创建将字符串转换为按字母或数字分组的另一个字符串的正则表达式:

$string = "cucumber";

正则表达式之后: ccuumber

$string = "tohothin";

经过正则表达式: ttoohhin

我怎样才能用PHP创建这个? 正则表达式并不重要,它可能是另一个函数。

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.

最满意答案

好吧,我没有看到一个尝试,但我很无聊:

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

产量: ccuumber

排序会起作用,但会给出不同的顺序:

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

产量: bccemruu

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

更多推荐