Implementation example of string matching KMP algorithm in php

Source: Internet
Author: User
Tags strlen

The kmp algorithm is an improved string matching algorithm. e. knuth and V. r. pratt and J. h. morris also discovered that it was called the Knut -- Morris -- Pratt operation (KMP algorithm ). The key to the KMP algorithm is to define a next function based on the given pattern string W1, m. The next function contains information about local matching of the pattern string.

Example

The code is as follows: Copy code

<? Php
/*

PHP implementation of string matching KMP algorithm

*/

Function KMP ($ str ){
$ K = array (0 );
$ M = 0;
$ StrLen = strlen ($ str );
For ($ I = 1; $ I <$ strLen; $ I ++ ){
If ($ str [$ I] ==$ str [$ M]) {
$ K [$ I] = $ K [$ i-1] + 1;
$ M ++;
} Else {
$ M = 0;
$ K [$ I] = $ K [$ M];
        }
    }
Return $ K;
}
 
// KMP search

Function KMPMatch ($ src, $ par ){
$ K = KMP ($ par );
 
$ SrcLen = strlen ($ src );
$ ParLen = strlen ($ par );
 
For ($ I = 0, $ j = 0; $ I <$ srcLen ;){
 
        
// Returns the exact matched position.

If ($ j = $ parLen) return $ I-$ j;
 
        
// Print the matching process

Echo $ I. "". $ j. "{$ src [$ I]}-{$ par [$ j]} <BR> ";
 
If ($ par [$ j] ===$ src [$ I]) {
            
// Record matching count

$ J ++;
$ I ++;
} Else {
If ($ j = 0 ){
$ I ++;
            }
$ J = $ K [$ J-1> = 0? $ J-1: 0];
        }
    }
Return false;
}
 
// Test availability

$ Src = 'BBC ABCDAB abcdababd ';
$ Par = 'ABCD ';
 
// Matching value

Echo "partially matched values:", implode ("", KMP ($ par), "<BR> ";
// Search for specific characters (strings) in a given string)

Echo KMPMatch ($ src, $ par), "<BR> ";
 
/*

Partial matching value: 0 0 0 0 1 2 0

0 0 B-A

B-A 1 0

C-A 2 0

3 0-

4 0 A-A

1 B-B

6 2 C-C

7 3 D-D

8 4 A-A

9 5 B-B

10 6-D

10 2-C

10 0-

A-A 11 0

12 B-B

C-C 13 2

14 3 D-D

15 4 A-A

16 5 B-B

C-D 17 6

17 2 C-C

18 3 D-D

19 A-A

20 5 B-B

D-D 21 6

15

*/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.