Home > Backend Development > PHP Tutorial > Example of php implementing the sunday algorithm of string matching algorithm

Example of php implementing the sunday algorithm of string matching algorithm

黄舟
Release: 2023-03-17 20:02:01
Original
5690 people have browsed it

In our development work, we often encounter various algorithms. I believe many friends also know the matching algorithm. StringThe matching algorithms are the ones we often use. Today we will give Let's introduce in detail an example of Sunday algorithm implementing string matching algorithm in PHP!

Example of php implementing the sunday algorithm of the string matching algorithm

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

Summary:

This article uses code examples to give you a more intuitive explanation of the Sunday algorithm that implements string matching algorithms in PHP. I believe that all my friends will have a better understanding. I hope it will be helpful to your work!

Related recommendations:

Maximum Forward Matching Algorithm PHP Implementation

The simplest string matching algorithm in php

Example of single string matching algorithm in php

The above is the detailed content of Example of php implementing the sunday algorithm of 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