Example of string matching algorithm implemented by PHP [Sunday algorithm], algorithm Sunday
This example describes the string matching algorithm-Sunday algorithm implemented by PHP. We will share this with you for your reference. The details are as follows:
The Sunday algorithm is a string matching algorithm proposed by Daniel M. Sunday in 1990. The core idea is: in the matching process, when the pattern string is found to be mismatched, the algorithm can skip as many characters as possible to perform the next matching, thus improving the matching efficiency.
<? Php/** @ param $ pattern string * @ param $ text string to be matched */function mySunday ($ pattern = '', $ text ='') {if (! $ Pattern |! $ Text) return false; $ pattern_len = mb_strlen ($ pattern); $ text_len = mb_strlen ($ text); if ($ pattern_len >=$ text_len) return false; $ I = 0; for ($ I = 0; $ I <$ pattern_len; $ I ++) {// assemble an array with the characters in pattern as the underlying value $ shift [$ pattern [$ I] = $ pattern_len-$ I ;} while ($ I <= $ text_len-$ pattern_len) {$ nums = 0; // Number of matched characters while ($ pattern [$ nums] ==$ text [$ I + $ nums]) {$ nums ++; if ($ nums = $ pattern_len) {return "The fir St match index is $ I \ n ";}} if ($ I + $ pattern_len <$ text_len & isset ($ shift [$ text [$ I + $ pattern_len]) {// determine whether the last character of the mode string is in the mode string $ I + = $ shift [$ text [$ I + $ pattern_len]; // alignment This character} else {$ I + = $ pattern_len; // directly slide pattern_len} $ text = "I am testing mySunday on Sunday! "; $ Pattern =" Sunday "; echo mySunday ($ pattern, $ text );
Running result:
The first match index is 25