Example of string matching algorithm implemented in PHP

jacklove
Release: 2023-04-02 15:44:01
Original
1775 people have browsed it

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 in need can refer to Next

The example in this article describes the string matching algorithm implemented by PHP——Sunday algorithm. Share it with everyone for your reference, the details are as follows:

The 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.

<?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

Run result:

The first match index is 25
Copy after login

Articles you may be interested in:

Example explanation of the maximum forward matching algorithm implemented in PHP

Installation and use of the PHP performance analysis tool xhprof Related notes

Explanation on the method of php encapsulating db class to connect to sqlite3 database

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

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