function MorrisPratt($text, $pattern) { $n = strlen($text); $m = strlen($pattern); $nextTable = array(); preprocessMorrisPratt($pattern, $nextTable); $i = $j = 0; while ($j < $n) { while ($i > -1 && $pattern[$i] != $text[$j]) { $i = $nextTable[$i]; } $i++; $j++; if ($i >= $m) { return $j - $i; } } return -1; }
/** * Performs a string search with the Morris-Pratt algorithm * * @param string $text * @param string $pattern */ function MorrisPratt($text, $pattern) { // get the text and pattern lengths $n = strlen($text); $m = strlen($pattern); $nextTable = array(); // calculate the next table preprocessMorrisPratt($pattern, $nextTable); $i = $j = 0; while ($j < $n) { while ($i > -1 && $pattern[$i] != $text[$j]) { $i = $nextTable[$i]; } $i++; $j++; if ($i >= $m) { return $j - $i; } } return -1; }