将字符串转换为按字母分组

时间:2016-11-15 18:36:38

标签: php

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

$string = "cucumber";

正则表达式后:ccuumber

$string = "tohothin";

正则表达式后:ttoohhin

我如何用PHP创建这个?它与正则表达式并不重要,它可能是另一种功能。

1 个答案:

答案 0 :(得分:5)

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

$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