Detailed explanation of PHP string matching algorithm

小云云
Release: 2023-03-18 06:18:01
Original
2842 people have browsed it

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. This article mainly introduces the string matching algorithm implemented by PHP, briefly describes the concept and principle of the sunday algorithm, and analyzes the related skills of PHP based on the sunday algorithm to implement string matching operations in the form of examples. Friends who need it can refer to it. I hope it can help. to everyone.

<?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);
Copy after login

Running result:

The first match index is 25
Related recommendations:

How to implement stack data structure and bracket matching algorithm in php Detailed code examples

The simplest string matching algorithm in php, php matching algorithm_PHP tutorial

The simplest characters in php String matching algorithm tutorial

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template