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

PHP按字符位置对比两字符串并返回差异字符数的实现问题

实现方案

你需要的严格按位置比对、差异计数包含长度差的需求,PHP原生的strcmp、similar_text都无法满足,可自行实现如下工具函数:

function get_position_diff_count(string $correct, string $user_answer): int
{
    // 先计算长度差异数
    $len_correct = strlen($correct);
    $len_answer = strlen($user_answer);
    $diff = abs($len_correct - $len_answer);
    // 遍历公共长度部分,逐位比对字符
    $min_len = min($len_correct, $len_answer);
    for ($i = 0; $i < $min_len; $i++) {
        if ($correct[$i] !== $user_answer[$i]) {
            $diff++;
        }
    }
    return $diff;
}

测试验证

你给出的所有测试用例均可通过:

  • get_position_diff_count('Monday', 'Manday') 返回 1
  • get_position_diff_count('Monday', 'Mondayy') 返回 1
  • get_position_diff_count('Hello', 'World') 返回 5

多字节字符适配

如果你的业务场景包含中文、emoji等多字节字符,需要替换为多字节处理函数避免统计错误,适配版本如下:

function get_mb_position_diff_count(string $correct, string $user_answer, string $encoding = 'UTF-8'): int
{
    $len_correct = mb_strlen($correct, $encoding);
    $len_answer = mb_strlen($user_answer, $encoding);
    $diff = abs($len_correct - $len_answer);
    $min_len = min($len_correct, $len_answer);
    for ($i = 0; $i < $min_len; $i++) {
        $char_correct = mb_substr($correct, $i, 1, $encoding);
        $char_answer = mb_substr($user_answer, $i, 1, $encoding);
        if ($char_correct !== $char_answer) {
            $diff++;
        }
    }
    return $diff;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:45:07