An example of a regular expression in PHP

Source: Internet
Author: User
Tags preg strong password
In the programming of the basic will use regular expression to deal with the data, then the following specific in PHP how to use it, this article through concrete examples, to explain the use of the PHP expression in the method.

Recently, using PHP to write an application, mainly the processing of regular expressions, the opportunity to systematically learn the corresponding knowledge.
The way this article is written is not to speak of theory, but to understand the regular by concrete examples, which is more practical, and on this basis to see the basic concept of regular expressions will be more fruitful.

Prohibit grouping of captures

Grouping in regular is useful, you can define a sub-schema, and then you can refer to the grouped content by a back reference, but sometimes you just want to use grouping to define the scope, rather than being grouped to capture it, with an example to understand:

$str = "http://www.google.com"; $preg = "/http:\/\/\w+\.\w+. (?: NET|COM|CN) +/is "; $preg 2="/http:\/\/\w+\.\w+. (NET|COM|CN) +/is ";p reg_match ($preg, $str, $arr);p Reg_match ($preg 2, $str, $arr 2);

When the pattern appears?: The grouping of the parentheses is not referenced, and the following example is used to understand it.

The difference between Preg_match () and Preg_match_all ()

Preg_match () matches the pattern at the end of the match, while Preg_match_all () makes a global match, with an example to understand:

$str = ' Hello World china '; $preg = "/\w+\s/is";p reg_match ($preg, $str, $arr);p rint_r ($arr);p Reg_match_all ($preg, $STR, $ ARR);p Rint_r ($arr);

Correct understanding of $ and ^

First say a regular, in order to match whether the phone number:

$str = "13521899942a"; $preg = "/1[\d]{3,15}/is"; if (Preg_match ($preg, $str, $arr)) {  echo "OK";}

Although there is an English letter in the string, but this sub-pattern is matched, the reason is that the pattern match to the end, will not look for the English alphabet, in order to solve the problem of the $ and ^ play a role, such as the beginning and end of the string must match a certain pattern, modified as follows:

$str = "13521899942a"; $preg = "/1[\d]{3,15}$/is"; if (Preg_match ($preg, $str, $arr)) {  echo "OK";}

The cross-line mode of $ and ^

By default, $ and ^ only match the beginning and end of a complete paragraph, but by changing the options, allowing the start and end of each line of the text to be matched, you can see by the following example

$str = ' HelloWorld '; $preg = '/\w+$/ism ';//$preg = '/(? m) \w+$/is ';p reg_match_all ($preg, $str, $arr);p Rint_r ($arr);

Group naming

After grouping by parentheses in the regular, you can use a number such as \1,\2 to make a back reference, but if there are too many patterns in the regular pattern, it will be confusing when used, so you can use the group naming to refer to it, and see an example:

$str = "email:ywdblog@gmail.com;"; Preg_match ("/email: (? <email>\w+?) /is ", $str, $matches); Echo $matches [" email "]. "_" . $matches [' No '];

Lazy mode

The regular match is greedy, as long as the matching pattern will always match, the following example, matching to the text is

$str = "

By changing an option can be modified to lazy mode, that is, once the match is aborted, the code is modified as follows:

$str = "

Further understanding of Preg_match_all ()

By the last parameter of this function, you can return an array of different forms:

$str = ' Jiangsu (Nanjing) Nantongguangdong (Guangzhou) zhuhaibeijing (Tongzhou) Haidian '; $preg = '/^\s*+ ([^ (]+?)] \s\ (([^)]+) \) \s+ (. *) $/m ';p reg_match_all ($preg, $str, $arr, Preg_pattern_order);p rint_r ($arr);p Reg_match_all ($preg , $str, $arr, Preg_set_order);p Rint_r ($arr);

Powerful regular replacement callbacks

Although the Preg_replace () function can do most of the substitutions, if you want better control, you can use callbacks, not to mention the example:

$STR = "China Hello world"; $preg = '/\b (\w+) (\w) \b/', function Fun ($m) {    return $m [1].strtoupper ($m [2]);} Echo Preg_replace_callback ($preg, "fun", $str);

At this point, PHP is much more powerful than python, and there is no regular callback in Python, but it can be solved by using closures, which can be seen in my previous article.

Preg_quote ()

This function is similar to the Re.compile () function in Python, and can be escaped if some metacharacters in the pattern simply want to express the meaning of the character itself, but it can be confusing to write too many escapes in the pattern, and use this function to uniformly escape:

$str = ' \\*china*world '; $preg = "\*china"; $preg = Preg_quote ($preg); Echo $preg;p reg_match ("/{$preg}/is", $str, $arr); Print_r ($arr);

Search forward? = the Magical

It may be more appropriate to explain in English:

The "? =" combination means "the next text must is like this". This construct doesn ' t capture the text.
(1) This example can get the protocol part of the URL, such as https,ftp, note that the following section is not in the returned content.

$str = "http://www.google.com"; $str = "https://www.google.com"; $preg = '/[a-z]+ (? =:)/';p reg_match ($preg, $str, $arr); Print_r ($arr);

(2) "Invisible" separator

Also known as the "Zero-width" delimiter, refer to the following example:

$str = ("Chinaworldhello"), $preg = "/(=[a-z])/"; $arr = Preg_split ($preg, $str);p Rint_r ($arr);

(3) Match strong password

Instead of specifying the order that things should appear, it's saying that it must appear but we ' re not worried about the Order.
The first grouping is (? =.{ 8,}). This checks if there is at least 8 characters in the string. The next grouping (? =.[ 0-9]) means "any alphanumeric character can happen zero or more times and then any digit can happen". So this checks if there are at least one number in the string. But since the string isn ' t captured, so one digit can appear anywhere in the string. The next groupings (? =.[ A-z]) and (? =.[ A-z] is looking for the lower case and upper case letter accordingly anywhere in the string.

$str = "HelloWorld2016"; if (Preg_match ("/^.* (? =.{ 8,}) (? =.*\d) (? =.*[a-z]) (? =.*[a-z]). *$/", $str, $arr)) {  print_r ($arr);}

Looking backwards? <=

<= means that if a specific character is matched, the content after that character is returned.
= indicates that the content preceding the character is returned if it is matched to a specific character.

$str = ' Chinadhello '; $preg = '/(? <=a) d (? =h)/';  Preg_match ($preg, $str, $arr);p Rint_r ($arr);

The above is the whole content of this article, I hope that everyone's study has helped.


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.