Find the longest common substring using PHP

I recently found a need to find the longest common substring in an array of strings in PHP. A couple of Google searches didn’t return any relevant solutions, so I decided to roll my own. I haven’t benchmarked this yet for large strings and/or arrays, but it does what I needed it to for my own purpose.


One thought on “0

  1. A little bit simpler solution, only for two strings.
    It returns string.

    function longestCommonSubstring( $str1, $str2, $case_sensitive=false)
    $ret = array();

    $len1 = mb_strlen($str1);
    $len2 = mb_strlen($str2);
    if (! $len1 || ! $len2)
    return false;

    // Find shorter
    if ($len2 < $len1)
    $t = $len1;
    $len1 = $len2;
    $len2 = $t;
    $t = $str1;
    $str1 = $str2;
    $str2 = $t;

    if (! $case_sensitive)
    $str1 = mb_strtolower($str1);
    $str2 = mb_strtolower($str2);

    // Through chars.
    for ($i = 0; $i<$len1; $i++)
    // Next char is same?
    $c1 = mb_substr($str1, $i, 1);
    if ($c1 === mb_substr($str2, $i, 1))
    $ret[] = $c1;


    return implode('', $ret);

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Previous post Training With Rebekah
Next post Asserting your domain expertise and learning to say “no” to your clients