PHP regular expression efficiency greedy, non-greedy, and backtracking analysis (recommended)

Source: Internet
Author: User
What is the greedy regular expression and what is non-greedy first? Or what is the matching priority measure and what is the ignoring priority measure. well, we will introduce the efficiency greedy, non-greedy, and backtracking analysis of PHP regular expressions through examples, let's take a look. what is the greedy regular expression and what is non-greedy? Or what is a match preference, and what is a ignore preference?

Well, I don't know what the concept is. let's give an example.

Some students want to filter the content between them. that's how they write regular expressions and programs.

$ Str = preg_replace ('% script. +? Script % I ', '', $ str); // non-greedy

It seems that there is no problem, but it is actually not. If

$str = '
 
  alert(document.cookie)《script》';
 

The result is as follows:

$ Str ='
 
  
Alert (document. cookie) script '; $ str = preg_replace (' % script. +? Script % I ', '', $ str); // non-greedy print_r ($ str); // $ str output as script alert (document. cookie) script
 

He still cannot achieve the desired effect. The above is not greedy, and some are also called inertia. The non-greedy logo is followed by a few characters? For example, +? ,*? ,?? (Special. I will write it in my BLOG later. That is, the logo is not greedy. if it is not written? Greedy. For example

$ Str ='
 
  
Alert (document. cookie) script '; $ str = preg_replace (' % script. + script % I ', '', $ str); // non-greedy print_r ($ str); // $ str output is
  
 

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.