Examples of Regular Expressions in PHP and php Regular Expressions

Source: Internet
Author: User
Tags preg

Examples of Regular Expressions in PHP and php Regular Expressions

Recently, I used PHP to write an application, mainly dealing with regular expressions, and systematically learned relevant knowledge.
The Writing Method of this article is not to talk about theory, but to understand regular expressions through specific examples. This is also more practical. On this basis, it will be more rewarding to look at the basic concepts of regular expressions.

Disable group capture

Grouping is useful in regular expressions. You can define sub-patterns and then reference the group content through backward references. However, you only want to define the range by grouping, instead of being captured by groups, you can see through an example:

$str = "http://www.google.com";$preg= "/http:\/\/\w+\.\w+.(?:net|com|cn)+/is";$preg2= "/http:\/\/\w+\.\w+.(net|com|cn)+/is";preg_match($preg,$str,$arr);preg_match($preg2,$str,$arr2);

What happens in the mode? : Indicates that the grouping of this bracket will not be referenced. You can understand it by running the example below.

Differences between preg_match () and preg_match_all ()

Preg_match () ends when a match is completed in the matching mode, while preg_match_all () performs global match. You can see through an example:

$str='hello world china';$preg="/\w+\s/is";preg_match($preg,$str,$arr);print_r($arr);preg_match_all($preg,$str,$arr);print_r($arr);

Correct understanding $ and ^

Let's talk about a regular expression first, to match whether it is a mobile 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, this sub-pattern matches. The reason is that after the match, the sub-pattern ends and no English letters are found, to solve this problem, $ and ^ play a role. For example, to make the start and end of a string match a certain pattern, modify the following:

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

Cross-row mode of $ and ^

By default, $ and ^ match only the beginning and end of the complete paragraph. However, by changing the options, the start and end of each line of the text can be matched, the following example shows how

$str='helloworld';$preg='/\w+$/ism';//$preg='/(?m)\w+$/is';preg_match_all($preg,$str,$arr);print_r($arr);

Group Name

After grouping by parentheses in a regular expression, you can use numbers such as \ 1, \ 2 for backward reference. However, if there are too many regular expressions in the regular expression, it will be confusing to use, in this case, the group name can be used for reference. Let's look at an example:

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

Lazy Mode

Regular Expressions are greedy during Matching. As long as the matching mode is met, the matching will continue. In the following example, the matched text is

$str = "

By changing an option, you can change it to the lazy mode. That is, once the match is reached, it will be aborted. The modification code is as follows:

$str = "

Further understanding of preg_match_all ()

The last parameter of this function can return arrays of different forms:

$str= 'jiangsu (nanjing) nantongguangdong (guangzhou) zhuhaibeijing (tongzhou) haidian';$preg = '/^\s*+([^(]+?)\s\(([^)]+)\)\s+(.*)$/m';preg_match_all($preg,$str,$arr,PREG_PATTERN_ORDER);print_r($arr);preg_match_all($preg,$str,$arr,PREG_SET_ORDER);print_r($arr);

Powerful Regular Expression replacement callback

Although the preg_replace () function can complete most of the replacements, you can use callback for better control. Let's look at the example below:

$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. There is no regular callback in Python, but it can be solved using closures. See my previous article.

Preg_quote ()

This function is similar to re. the compile () function can be escaped if some metacharacters only want to express the meaning of the characters in the mode, but it will be confusing if too many escape characters are written in the mode, you can use this function to unify the escape:

$str = '\\*china*world';$preg = "\*china";$preg = preg_quote($preg);echo $preg;preg_match( "/{$preg}/is",$str,$arr);print_r($arr);

Search forward? =

It may be more appropriate to explain in English:

The "? = "Combination means" the next text must be like this ". This construct doesn' t capture the text.
(1) In this example, we can obtain the protocol section in the URL, such as https and ftp. What should I do? : The following parts are not returned.

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

(2) "invisible" Separator

It is also called the "zero-width" separator. refer to the following example:

$str = ("chinaWorldHello");$preg = "/(?=[A-Z])/";$arr = preg_split($preg,$str);print_r($arr);

(3) Match strong passwords

Instead of specifying the order that things shoshould 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 are at least 8 characters in the string. The next grouping (? =. [0-9]) means "any alphanumeric character can happen zero or more times, then any digit can happen ". so this checks if there is at least one number in the string. but since the string isn' t captured, that one digit can appear anywhere in the string. the next groupings (? =. [A-z]) and (? =. [A-Z]) are 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);}

Search backward? <=

? <= Indicates that if a specific character is matched, the content after the character is returned.
? = Indicates that if a specific character is matched, the content before the character is returned.

$str = 'chinadhello';$preg = '/(?<=a)d(?=h)/';  preg_match($preg, $str, $arr);print_r($arr);

Now, let's take a look at this tutorial. If you have any questions, please leave a message. Let's discuss it.

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.