function Cal_next ($str) { $next [0] = -1;//next[0] is initialized to-1 $i =0; $j =-1; $len =strlen ($STR); while ($i < $len) { if ($j ===-1 | | $str [$i]=== $str [$j]) { $i + +; $j + +; $next [$i]= $j; } else{ $j = $next [$j]; } } return $next;} $str = ' abcdabd '; $next =cal_next ($STR); Var_dump ($next); function search ($STR, $search) { $next =cal_next ($search) ; $i =0; $j =0; $lenStr =strlen ($STR); $lenSearch =strlen ($search); while ($i < $lenStr && $j < $lenSearch) { if ($j ===-1 | | $str [$i]=== $search [$j]) { //$i The main string does not retreat, Move the pattern string. Why there is no $j===0, because if there is $j++ for 1, the next step is to judge $str[$i]=== $search [1], skipped $search[0] $i + +; $j + +; } else{ $j = $next [$j]; } } if ($j = = = $lenSearch) { return $i-$j; } return-1;} Var_dump (Search ($str, ' ABD '));
Reference
[KMP Algorithm (1): How to understand KMP] (https://segmentfault.com/a/1190000008575379) [KMP algorithm for string matching] (http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html) [KMP algorithm is the most superficial understanding] (https://blog.csdn.net/starstar1992/article/details/54913261)
function Cal_next ($str) { $next [0] = -1;//next[0] is initialized to-1 $i =0; $j =-1; $len =strlen ($STR); while ($i < $len) { if ($j ===-1 | | $str [$i]=== $str [$j]) { $i + +; $j + +; $next [$i]= $j; } else{ $j = $next [$j]; } } return $next;} $str = ' abcdabd '; $next =cal_next ($STR); Var_dump ($next); function search ($STR, $search) { $next =cal_next ($search) ; $i =0; $j =0; $lenStr =strlen ($STR); $lenSearch =strlen ($search); while ($i < $lenStr && $j < $lenSearch) { if ($j ===-1 | | $str [$i]=== $search [$j]) {//$i the main string does not rewind, move the mode string. Why there is no $j===0, because if there is $j++ for 1, the next step is to judge $str[$i]=== $search [1], skipped $search[0] $i + +; $j + +; } else{ $j = $next [$j]; } } if ($j = = = $lenSearch) { return $i-$j; } return-1;} Var_dump (Search ($str, ' ABD '));
Reference
[KMP Algorithm (1): How to understand KMP] (https://segmentfault.com/a/1190000008575379) [ KMP algorithm for string matching] (http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html) [ KMP algorithm is the most superficial understanding] (https://blog.csdn.net/starstar1992/article/details/54913261)