Tips for using regular expressions in PHP

Source: Internet
Author: User

PHP regular expressions are mainly used for pattern segmentation, matching, search, and replacement of strings. Regular expressions may be inefficient in some simple environments. Therefore, you need to consider how to better use PHP regular expressions.

My PHP Regular Expression entry is an article on the Internet. This article explains the PHP regular expression method from a simple perspective. I think it is a good entry-level material, however, it is still dependent on the individual who will continue to forget it when using it. Therefore, I read this article four or five times repeatedly. For some of the difficult knowledge points, it may take a long time to digest, but as long as you can stick to it, you will find that your use of regular expressions will significantly improve.

PHP Regular Expression definition:

A syntax rule used to describe character arrangement and matching modes. It is mainly used for string mode segmentation, matching, search and replacement operations.

Regular Functions in PHP:

PHP has two sets of regular functions, which have similar functions:

One set is provided by the PCRE (Perl Compatible regularexpression) Library. Functions with the prefix "prefix;

A set of extensions provided by POSIX (Portable Operating System Interface of UNIX. Use a function named with the prefix "ereg _". (POSIX Regular Expression Library is not recommended since php5.3 and will be removed from PhP6)

Since POSIX regular expressions are coming soon, And the PCRE and Perl forms are similar, it is more conducive to switching between Perl and PHP, so here we will focus on the use of PCRE regular expressions.

PCRE Regular Expression

PCRE is called Perl Compatible Regular Expression, which means Perl is compatible with regular expressions.

In PCRE, a pattern expression (that is, a regular expression) is usually included between two Backslash "/", such as "/Apple /".

There are several important concepts in Regular Expressions: metacharacters, escaping, pattern units (duplicates), assignees, references, and assertions, these concepts can be easily understood and mastered in article [1.

Frequently Used metacharacters (meta-character ):

Metacharacters   Description

\     Matches the atom at the beginning of a string.

\ Z     Matches the atoms at the end of a string.

\ B     Match the word boundary   /\ BIS/ Matching string with the header "is" /Is \ B/ Match the string whose tail is /\ Bis \ B/demarcation

\ B     Match any character except word boundary /\ BIS/ Match "is" in the word "this"

\ D   Matches a number. It is equivalent to [0-9].

\ D   Matches any character except a number. It is equivalent to [^ 0-9].

\ W   Matches an English letter, number, or underline. It is equivalent to [0-9a-za-z _]

\ W   Matches any character except English letters, numbers, and underscores. It is equivalent to [^ 0-9a-za-z _].

\ S   Matches a blank character. It is equivalent to [\ f \ t \ v].

\ S   Matches any character except the blank character. It is equivalent to [^ \ f \ t \ v]

\ F   Matching a page feed is equivalent to \ x0c or \ Cl.

Match a line break; equivalent to \ x0a or \ CJ

Matching a carriage return is equivalent to \ x0d or \ cm.

\ T   Match a tab. It is equivalent to \ x09 \ or \ Cl.

\ V   Match a vertical tab; equivalent to \ x0b or \ CK

\ Onn Matches an octal number.

\ Xnn Matches a hexadecimal number.

\ CC  Match A Control Character

Pattern modifiers ):

Pattern delimiters are used in case-insensitive and multi-row matching. These delimiters often solve many problems.

I   -Uppercase and lowercase letters can be matched simultaneously.

M   -Treat strings as multiple rows

S   -The string is treated as a single line, and the line break is treated as a common character so that "." matches any character.

X   -The white space in the mode is ignored. 

U   -Match the nearest string

E   -Use the replaced string as an expression

Format:/Apple/I matches "apple" or "apple", and case insensitive.   /I

PCRE mode unit:

// 1. Extract the first attribute

/^ \ D {2} ([\ W]) \ D {2 }\\ 1 \ D {4} $ matches strings such as "12-31-2006", "09/27/1996", and "86 014321. However, the above regular expression does not match the "12/34-5678" format. This is because the result "/" of the mode "[\ W]" has been stored. When the next position "\ 1" is referenced, the matching mode is also the character "/".

When you do not need to store matching results, use the non-storage mode unit "(? :)"

For example /(? : A | B | C) (d | E | f) \ 1g/will match "AEEG ". In some regular expressions, it is necessary to use non-storage mode units. Otherwise, you need to change the subsequent reference sequence. The preceding example can also be written as/(A | B | C) (C | E | f) \ 2g /.

 

PCRE regular expression function:

Preg_match () and preg_match_all ()
Preg_quote ()
Preg_split ()
Preg_grep ()
Preg_replace ()

For specific functions, we can find them in the PHP manual. Below are some accumulated Regular Expressions:

Matching action attributes

 

$ STR = '';
$ Match = '';
Preg_match_all ('/\ s + action = \"(?! HTTP :)(.*?) \ "\ S/', $ STR, $ match );
Print_r ($ match );

Use callback in Regular Expressions

 

Function callback_replace (){
$ Url = 'HTTP: // esfang.house.sina.com.cn ';
$ STR = '';
$ STR = preg_replace ('/(? <= \ Saction = \")(?! HTTP :)(.*?) (? = \ "\ S)/E', 'search (\ $ URL, \ 1) ', $ Str );

Echo $ STR;
}

Function search ($ URL, $ match ){
Return $ URL. '/'. $ match;
}

Regular Expression matching with assertions

 

$ Match = '';
$ STR = 'xxxxxx .com.cn bold font
Paragraph text

';
Preg_match_all ('/(? <= <(\ W {1})> ).*(? = <\/\ 1>)/', $ STR, $ match );
Echo "matches the content in HTML tags without attributes :";
Print_r ($ match );

Replace the address in the HTML source code

 

$ Form_html = preg_replace ('/(? <= \ Saction = \ "| \ SSRC = \" | \ shref = \")(?! HTTP: | JavaScript )(.*?) (? = \ "\ S)/E ', 'add _ URL (\ $ URL, \' \ 1 \ ')', $ form_html );

Finally, although the regular expression tool is powerful, in terms of efficiency and writing time, sometimes it may not be as direct as explode. For some urgent or less demanding tasks, A simple and crude method may be better.

 Backward reference

After a subexpression is specified with parentheses, the text matching the subexpression can be further processed in the expression or other programs. By default, each group will automatically have a group number. The rule is: from left to right, marked by the left parentheses of the group, and the first group number that appears is 1, the second is 2, and so on.

Backward reference is used to repeatedly search text matched by the previous Group. For example, \ 1 indicates the text matched by Group 1. Hard to understand? See the example:

\ B (\ W +) \ B \ s + \ 1 \ B can be used to match duplicate words, such as go and kittykitty. The first is a word, that is, more than one letter or number (\ B (\ W +) \ B) between the start and end of a word ), then there is one or several blank characters (\ s +, and finally the matched word (\ 1 ).

You can also specify the group number or group name of the subexpression. To specify the group name of a subexpression, use the following syntax :(? <Word> \ W +), so that the Group Name of \ W + is specified as word. To reverse reference the content captured by this group, you can use \ K <word>, so the previous example can also be written as follows: \ B (? <Word> \ W +) \ B \ s * \ K <word> \ B.

When parentheses are used, there are many syntax for specific purposes. The most common ones are listed below:

Table 4. Group syntax capture (exp) matches exp and captures text to automatically named groups (? <Name> exp) matches exp and captures the text to a group named name. It can also be written (? 'Name' exp )(? : Exp) matches exp, and the position of the matched text is not captured (? = Exp) match the position (? <= Exp) matches the position (?! Exp) the position behind the matching is not the exp position (? <! Exp) match the position comment (? # Comment) this type of group does not affect the processing of regular expressions, but we have discussed the first two syntaxes to help people read comments. Third (? : Exp) does not change the processing method of the regular expression, but the content of such a group match will not be captured into a group as in the first two methods.

Location specified

The following four items are used to search for things before or after some content (but not including the content), that is, they are used to specify a location, just like \ B, ^, $, therefore, they are also called assertion with zero width. We 'd better illustrate it with examples:

(? = Exp) is also called the zero-width predicate. It matches certain positions in the text. These positions can be followed by the given suffix exp. For example, \ B \ W + (? = Ing \ B), matches the first part of the word ending with ing (except for ING. it will match sing and danc.

(? <= Exp) is also called the assertion with Zero Width. It matches certain positions in the text and matches exp with the given prefix. For example (? <= \ BRE) \ W + \ B will match the second half of the word starting with RE (Except re). For example, it matches ading when searching for readinga book.

If you want to add a comma (, of course, from the right side) to each of the three digits in a long number, you can search for the parts that need to be added with a comma :((? <= \ D) \ D {3}) * \ B. Please analyze this expression carefully. It may not be as simple as what you first see.

The following example uses both the prefix and Suffix :(? <= \ S) \ D + (? = \ S) match the numbers separated by spaces (emphasize again, do not include these spaces ).

Specified negative position

We have previously mentioned how to find out characters that are not a character or are not in a character class ). But what if we only want to ensure that a character does not appear, but do not want to match it? For example, if we want to find such a word, which contains the Letter Q, but Q is not followed by the letter U, we can try this:

\ B \ W * Q [^ u] \ W * \ B matches a word that contains the Letter Q, not the letter U. But if you do more tests (or if you are keen enough, you can simply observe them), you will find that if q appears at the end of a word, like Iraq, BenQ, this expression will cause an error. This is because [^ u] Always matches one character, so if Q is the last character of a word, the [^ u] Following will match the word separator (which may be a space, a full stop or something else) after Q, And the \ W + \ B Following will match the next word, therefore, \ B \ W * Q [^ u] \ W * \ B can match the entire iraqfighting. The specified negative position can solve this problem because it only matches one position and does not consume any characters. Now, we can solve this problem as follows: \ B \ W * q (?! U) \ W * \ B.

Assertion (?! Exp), only matching the position where the suffix exp does not exist. \ D {3 }(?! \ D) matches three digits, and the three digits cannot be followed by digits.

Similarly, we can use (? <! Exp), and the assertion is performed to find the position where the prefix exp does not exist :(? <! [A-Z]) \ D {7} match the first seven digits that are not lowercase letters (error found in the experiment? Note whether your "case sensitive" item is selected first ).

A more complex example :(? <= <(\ W +)> ).*(? = <\/\ 1>) matches the content in the simple HTML Tag that does not contain the attribute. (& Lt ;? (\ W +)>) specifies the prefix: The word enclosed by Angle brackets (for example, <B>), and then. * (any string), followed by a suffix (? = <\/\ 1> ). Pay attention to the \/In the suffix, which uses the character escape mentioned above; \ 1 is a reverse reference, which references the first group captured, the previous (\ W +) if the prefix is <B>, the suffix is </B>. The entire expression matches the content between <B> and </B> (remind me again, excluding the prefix and suffix itself ).

Greed and laziness

When a regular expression contains a qualified qualifier (a specified number of codes, such as *, {5, 12, the common behavior is to match as many characters as possible (on the premise that the entire expression can be matched. Consider this expression: A. * B, which will match the longest string starting with a and ending with B. If you use it to search for aabab, it will match the entire string aabab. This is called greedy matching.

Sometimes, we need to be more lazy to match, that is, to match as few characters as possible. All the qualifiers given above can be converted to the lazy match mode, as long as a question mark is added after it ?. This way .*? This means to match any number of duplicates, but use the minimum number of duplicates if the entire match is successful. Now let's look at the lazy version example:

A .*? B matches the string that is shortest, starts with a, and ends with B. If it is applied to aabab, it will match AAB and AB (why is the first match AAB instead of AB? To put it simply, the first primary partition has the highest priority-thematch that begins earliest wins ).

Table 5. Lazy qualifier *? Repeat any time, but as few as possible +? Repeat once or more times, but as few as possible ?? Repeated 0 or 1 times, but as few as possible {n, m }? Repeat n to m times, but try to repeat {n ,}? Repeated more than N times, but as few as possible

Balance Group

If you want to match a hierarchy that can be nested, you have to use a balance group. For example, how can we capture the content in the longest brackets in a string like "XX <AA <BBB> AA> YY?

The following syntax structure is required:

(? <Group>) Name the captured content as a group and press it into the stack.

(? <-Group>) from the stack, the capture content named group that is pushed into the stack is displayed. If the stack is empty, the matching of the group fails.

(? (Group) Yes | no) if the capture content named group exists on the stack, continue to match the expression of the yes part; otherwise, continue to match the no part.

(?!) Assertion with Zero Width and negative direction, attempts to match always fail because there is no suffix expression

If you are not a programmer (or you are a programmer unfamiliar with the concept of stack), you can understand the above three syntaxes: the first is to write one (or another) "group" on the blackboard, and the second is to erase a "group" from the blackboard ", the third is to check whether there is a "group" written on the blackboard. If there is a group, continue to match the "yes" section; otherwise, match the "no" section.

What we need to do is to write a "group" on the blackboard every time we encounter a left bracket. Every time we encounter a right bracket, We will erase one, at the end, let's see if there is any on the blackboard.-if there are more left brackets than right brackets, the matching should fail. (To make it clearer, I used it (? 'Group') syntax ):

<         # Left parenthesis of the outermost layer

   [^ <>] *       # The left parenthesis behind the outermost layer is not the content of the parentheses.

  ( (  (? 'Open' <)   # Write an "open" on the blackboard when you encounter a left bracket"

   [^ <>] *     # Matching the content behind the left parenthesis is not the content of the brackets

   ) + (  (? '-Open'>)# Remove an "open" from the brackets"

    [^ <>] *     # Matching content not enclosed by brackets

   ) + )* (? (Open )(?!)) # In front of the outermost right parenthesis, check whether there is any "open" on the blackboard that has not been erased. If there are still, the match fails.

>        
# Right parenthesis of the outermost layer

 

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.