This article describes the string matching algorithm implemented by PHP—————————————————————————————————————————————————————————————————————————————————————————————————————————————————— Share it for your reference, as follows:
The Sunday algorithm is a string pattern matching proposed by Daniel in 1990. The core idea is:During the matching process, when a pattern string finds a mismatch, the algorithm can skip as many characters as possible to perform the next match, thereby improving the matching efficiency.
<?php /* *@param $pattern 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 characters in pattern as subscript $shift[$pattern[$i]] = $pattern_len - $i; } while($i <= $text_len - $pattern_len){ $nums = 0; //The number of characters on the match while($pattern[$nums] == $text[$i + $nums]){ $nums++; if($nums == $pattern_len){ return "The first match index is $i\n"; } } if($i + $pattern_len < $text_len && isset($shift[$text[$i + $pattern_len]])){ //Judge whether the character after the mode string is in the mode string $i += $shift[$text[$i + $pattern_len]]; //Align the character }else{ $i += $pattern_len; //Slide the pattern_len bit directly } } } $text = "I am testing mySunday on sunday!"; $pattern = "sunday"; echo mySunday($pattern,$text);
Running results:
The first match index is 25
For more information about PHP related content, please check out the topic of this site:PHP data structure and algorithm tutorial》、《Summary of PHP Programming Algorithm》、《Summary of usage of php strings》、《Complete collection of PHP array (Array) operation techniques》、《Summary of common traversal algorithms and techniques for PHP"and"Summary of PHP mathematical operation skills》
I hope this article will be helpful to everyone's PHP programming.