duandi8544 2014-12-10 03:20
浏览 73

PHP从头开始查找公共子串的范围

I have two strings which starts out the same, but at some point are different. I want to find how many characters the two strings share in common.

It seems like strpos is the opposite of this; it assumes that one string is found completely in another, but not necessarily at the starting offset.

I see a lot of questions which ask about finding common substrings when they aren't at the start, or when there are more than two strings, and this seems to complicate things quite a bit. I have just two strings, and they have a common prefix. IS there a PHP function to get the index at which these two strings differ?

  • 写回答

2条回答 默认 最新

  • donglu6303 2014-12-10 03:32
    关注

    You can try using for loop by comparing character by character. Something like this

    $str1 = 'MyStringFirst';
    $str2 = 'MyStringSecond';
    $match_from_left = '';
    $count = 0;
    $limit = strlen($str1) > strlen($str2) ? strlen($str2) : strlen($str1);
    for($i = 0; $i < $limit; $i++){
        if($str1[$i] != $str2[$i]){
            break;
        } 
        $count++;
        $match_from_left .= $str1[$i];
    }
    
    echo 'Count: ' . $count . '<br />';
    echo 'Match: ' . $match_from_left . '<br />';
    
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)