PHP Regular Expression Recommendation _ Regular expression

Source: Internet
Author: User
Tags comments modifier php regular expression
Mind Mapping
Click on the picture below, you can see the specific content!
introduce

Regular expression, we should be often used in the development, now many development languages have regular expression of the application, such as javascript,java,.net,php, and so on, I today to the regular expression of understanding with you Lao Lao, improper place, please advise!

Terms to know--what do you know about the following terms?

Δ delimiter
Δ character Field
Δ modifier
Δ Qualifier
Δ off character
Δ wildcard character (forward check, reverse check)
Δ Reverse Reference
Δ Lazy Match
Δ Comment
Δ 0 Words wide

positioning

When do we use regular expressions? Not all character operations are good, PHP in some ways, but the effect of efficiency. When we encounter the parsing of complex text data, it is a better choice to use the positive.

Advantages

Regular expressions, when dealing with complex character operations, can improve productivity and save you a certain amount of code.

Disadvantage

When we use regular expressions, complex regular expressions increase the complexity of the code, making it difficult to understand. So we sometimes need to add comments inside the regular expression.

Common Mode

¤ Delimiters, usually using "/" as a delimiter to start and end, you can also use "#".
When do you use "#"? Typically there are a lot of "/" characters in your string, because the characters need to be escaped, such as URIs.
The code that uses the "/" delimiter is as follows.
Copy Code code as follows:

$regex = '/^http:\/\/([\w.] +) \/([\w]+) \/([\w]+) \.html$/i ';
$str = ' http://www.youku.com/show_page/id_ABCDEFG.html ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

$matches[0] In Preg_match will contain a string that matches the entire pattern.
The code that uses the "#" delimiter is as follows. This time the "/" is not escaped!
Copy Code code as follows:

$regex = ' #^http://([\w.] +)/([\w]+)/([\w]+) \.html$ #i ';
$str = ' http://www.youku.com/show_page/id_ABCDEFG.html ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

¤ modifier: Used to change the behavior of a regular expression.
We see ('/^http:\/\/[\w.] +) The last "I" in \/([\w]+) \/([\w]+) \.html/i ') is a modifier that ignores case, and one of the most common uses of "X" is to ignore spaces.
Contribution code:

Copy Code code as follows:

$regex = '/hello/';
$str = ' Hello word ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Echo ' No i:valid successful! ', ' \ n ';
}
if (Preg_match ($regex. ' I ', $str, $matches)) {
Echo ' YES i:valid successful! ', "\ n";
}


¤ Character Value field: [\w] The part that expands with square brackets is the character field.

¤ Qualifiers: Symbols that are followed by [\w]{3,5} or [\w]*] or [\w] represent qualifiers. The specific meaning is introduced.
{3,5} represents 3 to 5 characters. {3,} more than 3 characters, {, 5} up to 5, {3} three characters.
* Represents 0 to many
+ represents 1 to many.

¤ Sign off character
^:
> put in the Word value field (such as: [^\w]) to express the negation (not included)--"Reverse selection"
> precede the expression to indicate the start of the current character. (/^n/i, which means beginning with n).
Note that "\" is called "Jump off character". Used to escape some special symbols, such as ".", "/"

wildcard character (Lookarounds): asserts that certain characters in certain strings exist or not!

Lookarounds are divided into two types: Lookaheads (Forward-check) and lookbehinds (reverse-check? <=).
> Format:
Forward check: (? =) corresponding to (?!) To express a negative meaning
Reverse check: (? <=) corresponding to (? <!) To express a negative meaning
Follow character before and after
Copy Code code as follows:
$regex = '/(<=c) d (? =e)/'; /* d front followed by C, D followed by e*/
$str = ' abcdefgk ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

Negative meaning:
Copy Code code as follows:
$regex = '/(? <!c) d (?! e)/'; /* d not immediately followed by C, D not followed by e*/
$str = ' abcdefgk ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";


> Character width: 0
Verifying 0 Character Codes
Copy Code code as follows:
$regex = '/he (=l) lo/i ';
$str = ' HELLO ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

Can't print out the results!
Copy Code code as follows:
$regex = '/he (=l) llo/i ';
$str = ' HELLO ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

Can print out the results!
Description: (? =l) means that he is followed by an L character. But (? =l) itself does not take up characters, to be distinguished from (l), (l) itself a character.
Capturing data
Groupings that do not have a type specified will be fetched for later use.
> indicates that the type refers to a wildcard character. Therefore, only parentheses starting position without question mark can be captured.
> references within the same expression are called reverse references.
> Calling format: \ number (such as \1).
Copy Code code as follows:
$regex = '/^ (Chuanshanjia) [\w\s!] +\1$/';
$str = ' Chuanshanjia thank Chuanshanjia ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

> Avoid capturing data
Format: (?:p Attern)
Advantages: The number of effective reverse references will be kept to a minimum, the code more clear.
> Named Capture Group
Format: (? p< Group name >) calling method (?) p= Group name)
Copy Code code as follows:
$regex = '/(? P<author>chuanshanjia) [\s]is[\s] (? P=author)/I ';
$str = ' Author:chuanshanjia is Chuanshanjia ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

Run results

Lazy Match (remember: Two actions will be performed, please see the principle section below)

Format: Qualifier?

Principle: First match "?" The previous section, then the right expression, and the right expression matches the success and the entire match ends.

First look at the following two code:

Code 1.
Copy Code code as follows:
$regex = '/(") [^\1]+\1/i ';
$str = ' "A" "B" "C" "D" ";
$matches = Array ();

if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}

echo "\ n";

Results 1.

Code 2
Copy Code code as follows:
$regex = '/(") [^\1]+?\1/i ';
$str = ' "A" "B" "C" "D" ";
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

Result 2

Analysis:
Compares two regular expressions: the first one adds "?" and the second one does not.
Results: The first argument is the first one that prints all the characters, and the second prints only a "a".
Conclusion:
>> first Meet (") [^\1]+\1 conditions are
"A", "a" "B", "a" "B" "C", "a" "B" "C" "D", "B", "B" "C", "B" "C" "D", "C", "C" "D", "D"
The first regular expression, however, chooses the largest "a" "B" "C" "D", stating that a non-inert match will compare the maximum matching result.
>> second regular expression: first match (") [^\1]+, if the match succeeds, then we are matching"? "\1 on the right, and if the match succeeds, the entire match ends."
Other cases:
"Oh, \" my\ "God" =====>/(") ([^\1] | \\1) *? (? <!\\) \1/i
Comments for regular expressions
Format: (? # comment Content)
Purpose: Mainly used in complex annotations
Contribution code: is a regular expression used to connect to the MySQL database
Copy Code code as follows:
$regex = '/
^host= (? <!\.) ([\d.] +)(?! \.) (? #主机地址)
\|
([\w!@#$%^&* () _+\-]+) (? #用户名)
\|
([\w!@#$%^&* () _+\-]+) (? #密码)
(?! \|) $/ix ';
$str = ' host=192.168.10.221|root|123456 ';
$matches = Array ();
if (Preg_match ($regex, $str, $matches)) {
Var_dump ($matches);
}
echo "\ n";

Special Characters
Special characters Explain
* 0 to many times
+ 1 to several times can also be written as {1}
? 0 or 1 times
. Matches all individual characters except for line breaks
\w [A-za-z0-9_]
\s White space characters (spaces, line breaks, carriage returns) [\t\n\r]
\d [0-9]

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.