You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现字符串按小写>大写>数字>符号优先级排序求助

你当前代码使用的rsort内置排序逻辑不符合题目要求的「小写字母>大写字母>数字>符号」优先级规则,需要通过PHP的自定义排序函数usort实现规则匹配的排序,完整可运行代码如下:

function customSortString($string) {
    // 把字符串拆分为单个字符的数组
    $chars = str_split($string);
    // 自定义排序回调
    usort($chars, function($a, $b) {
        // 给不同类型字符分配权重,权重越小排序越靠前
        $getWeight = function($c) {
            if (ctype_lower($c)) return 1;
            if (ctype_upper($c)) return 2;
            if (ctype_digit($c)) return 3;
            return 4;
        };
        $weightA = $getWeight($a);
        $weightB = $getWeight($b);
        // 权重不同时按权重升序排列
        if ($weightA !== $weightB) {
            return $weightA - $weightB;
        }
        // 权重相同时按ASCII码降序排列,匹配示例输出的同类型顺序
        return ord($b) - ord($a);
    });
    // 把排序后的数组合并为字符串返回
    return implode('', $chars);
}

// 原有调用逻辑适配修改
if(isset($_POST['input']) && !empty($_POST['input'])){
    echo '<pre>';
    echo 'Before sort: ';
    print_r($_POST['input']);
    echo '<br>--------------------<br>';
    echo 'After sort:' ;
    print_r(customSortString($_POST['input'])); 
    echo '</pre>';
}

把你原有代码里的reverseString函数替换为上述customSortString,再调整调用部分即可得到和示例一致的输出。

内容的提问来源于stack exchange,提问作者Luqman Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:15:01