Example of string matching algorithm implemented by PHP [Sunday algorithm], algorithm Sunday

Source: Internet
Author: User

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 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.