【问题标题】:Find multiple differences between two strings查找两个字符串之间的多个差异
【发布时间】:2011-04-20 09:35:58
【问题描述】:

我想找出两个字符串之间的差异。例如,如果

line1 = "My name is ABC"
line2 = "My age is xyz"

那么我应该能够得到名字-年龄和ABC-xyz的区别。

我想我可以使用 Levenshtein 距离,但无法弄清楚。非常感谢任何帮助。

【问题讨论】:

    标签: design-patterns distance levenshtein-distance


    【解决方案1】:
    <?php
    $line1 = "My name is ABC";
    $line2 = "My age is xyz";
    
    $matchlen = strspn($line1, $line2);
    
    // remove 1st non-matching char
    $same = substr($line1, 0, $matchlen - 1);
    
    // include 1st non-matching char
    $diff = substr($line2, $matchlen - 1);
    
    printf("Same: [%s]\nDiff: [%s]", $same, $diff);
    ?>
    

    【讨论】:

    • 这将无法正常工作,因为第一个区别在长度上不匹配:name : 4age : 3
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2012-02-09
    • 2012-03-10
    相关资源
    最近更新 更多