Home  >  Article  >  Backend Development  >  Detailed explanation and cases of sunday algorithm of PHP matching algorithm

Detailed explanation and cases of sunday algorithm of PHP matching algorithm

墨辰丷
墨辰丷Original
2018-05-16 17:32:391090browse

This article mainly introduces the detailed explanation and cases of the sunday algorithm of PHP matching algorithm. Interested friends can refer to it. I hope it will be helpful to everyone.

Sunday algorithm is a string pattern matching proposed by Daniel M.Sunday in 1990. The core idea is: during the matching process, when the pattern string is found to be unmatched, the algorithm can skip as many characters as possible for the next step of matching, thus improving the matching efficiency.

The case is as follows:

<?php
/*
 *@param $pattern 模式串
 *@param $text 待匹配串
 */
function mySunday($pattern = &#39;&#39;,$text = &#39;&#39;){
  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++){ //组装以pattern中的字符为下标的数组
    $shift[$pattern[$i]] = $pattern_len - $i;
  }
  while($i <= $text_len - $pattern_len){
    $nums = 0;   //匹配上的字符个数
    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]])){ //判断模式串后一位字符是否在模式串中
      $i += $shift[$text[$i + $pattern_len]];   //对齐该字符
    }else{
      $i += $pattern_len;   //直接滑动pattern_len位
    }
  }
}
$text = "I am testing mySunday on sunday!";
$pattern = "sunday";
echo mySunday($pattern,$text);

Running results:

The first match index is 25

Related recommendations:

Explanation of PHP stack data structure and bracket matching algorithm examples

Detailed explanation of PHP string matching algorithm

Example of PHP implementing string matching algorithm sunday algorithm

The above is the detailed content of Detailed explanation and cases of sunday algorithm of PHP matching algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn