note 18083 added to ref.strings

From: Date: Thu, 10 Jan 2002 01:27:28 +0000
Subject: note 18083 added to ref.strings
Groups: php.notes 
Request: Send a blank email to php-notes+get-24605@lists.php.net to get a copy of this message
I've ported a function to PHP that will find the longest common substring in two different strings. Here it is: function LongestCommonSubstring($string1, $string2) { // find length of longest common substring first $L = array(); $length1 = strlen($string1); $length2 = strlen($string2); for ($i = $length1; $i >= 0; $i--) { for ($j = $length2; $j >= 0; $j--) { if ($string1[$i] == '' || $string2[$j] == '') $L[$i][$j] = 0; elseif ($string1[$i] == $string2[$j]) $L[$i][$j] = 1 + $L[$i + 1][$j + 1]; else $L[$i][$j] = max($L[$i + 1][$j], $L[$i][$j + 1]); } } // then find the actual substring $substring = ''; $i = 0; $j = 0; while ($i < $length1 && $j < $length2) { if ($string1[$i] == $string2[$j]) { $substring .= $string1[$i]; $i++; $j++; } elseif ($L[$i + 1][$j] >= $L[$i][$j + 1]) $i++; else $j++; } return $substring; } Here is where I found the original: http://www1.ics.uci.edu/~eppstein/161/960229.html -- http://www.php.net/manual/en/ref.strings.php http://master.php.net/manage/user-notes.php?action=edit+18083 http://master.php.net/manage/user-notes.php?action=delete+18083 http://master.php.net/manage/user-notes.php?action=reject+18083

« previous php.notes (#24605) next »