PHP Learning-Regular expressions

Source: Internet
Author: User

PHP Learning-Regular expression 1, what is a regular expression

A regular expression is a logical formula for the amount of string processing, that is, a string that is combined into a rule with a particular string, called a regular matching pattern.

$p = '/apple/'; $str = ' Apple Banna ',if (Preg_match ($p, $str)) {  ' matched ';  }

Where the string '/apple/' is a regular expression used to match the existence of an apple string in a string.

PHP uses the Pcre library function for regular matching, such as the preg_match used in the previous example to perform a regular match, commonly used to determine whether a class of character patterns exist.

2. Basic syntax for regular expressions

In the Pcre library function, the regular match pattern consists of a delimiter and a meta string, which can be used to make any character that is not a number, backslash, or space. Frequently used delimiters are forward slashes (/), hash symbols (#), and inverse symbols (~), such as

/foo bar/#^[^0-9]$#~php~

If the regular form contains delimiters, the delimiter needs to be escaped with a backslash (\).

/http:\/\//

If the pattern contains more delimiters, it is recommended that you change other characters as separators, or you can use Preg_quote to escape.

$p = ' http://'; $p = '/'. Preg_quote ($p, '/'). ' /'; Echo $p;

Pattern modifiers can be used after delimiters, including: i,m,s,x, etc., such as using modifiers to ignore case

$str = ' http://www.baidu.com '; if (preg_match('/http/i ',$str)) {  echo ' match succeeded ';  }

3. Metacharacters and Escapes

Regular expressions have special meanings for characters that become metacharacters, and commonly used characters are:

\ General Escape character

^ Assert the starting position of the grinding edge (or the beginning of the line in multiline mode)

$ assert the end position of the Shepherd Whip (or line end at multiple lines)

. Match any character except line break (default)

[Start character class definition

] End character class definition

(The start tag of a child group

) The end tag of the child group

? As a quantifier, represents 0 or 1 matches, located two times the greedy character of the word used to change the variable (check quantifier)

* quantifier, 0 or more matches.

+ quantifiers, 1 or more matches

} The beginning of a custom quantifier

{End of custom quantifier

// the \s below represents any whitespace character, including spaces, tabs, and newline characters. [^\s] represents a non-whitespace character. [^\s]+ means one or more matches of non-whitespace.]  $p = '/^ me [^\s]+ (Apple | banana) $/'; $str = "I like to eat apples"; if (preg_match($p,$str)) {  echo ' match succeeded ';  }

Metacharacters has two usage scenarios, one that can be used anywhere and one that can only be used in square brackets, only in square brackets:

\ escape Character

^ Just as the first character (inside the square brackets), denotes the character inversion

-Marker Character Range

Where ^ is outside the parenthesis, indicating the starting position of the assertion target, but inside the square brackets means that the matching character class is reversed, the minus sign in square brackets-can mark the range of characters, for example: 0-9 represents all numbers from 0 to 9 self-test.

// The following \w match letters or numbers or underscores $p = '/[\w\.\-][email protected][a-z0-9\-]+\. (COM|CN)/'; $str = "My mailbox is [email protected]"; Preg_match ($p,$str,$match); Echo $match;

4. Greedy mode and lazy mode

Each meta-character in a regular expression matches one character, and when using + will become greedy, it will match as many characters as possible, but with a question mark? character, it would have been possible to match characters less, even in lazy mode.

Greedy mode: When it can match and not match, the first match

// the following \d represent a matching number $p = '/\d+\-\d+/'; $str = ' My phone is 101-12345678 '; Preg_match ($p,$str,$match); Echo $match [0]; Results 101-12345678

Lazy mode: Priority mismatch when matched and not matched

// the following \d represent a matching number $p = '/\d+\-\d+/'; $str = ' My phone is 101-12345678 '; Preg_match ($p,$str,$match); Echo $match [0]; Results 0-1

You can use {} to customize the number of matching characters when we know exactly the length of the match

// the following \d represent a matching number $p = '/\d{3}\-\d{8}/'; $str = ' My phone is 101-12345678 '; Preg_match ($p,$str,$match); Echo $match // result 0-1

5. Use regular expressions to match

6. Find all matching results

7. Search and replace when growing the form

8, regular matching common cases

Regular matching is commonly used in form validation, some fields will have a certain format requirements, such as the user name is generally required to be letters, numbers or underscores, mailboxes, telephones and so on have their own rules, so use regular expressions can be very good validation of these fields. We take a look at the General User registration page and how to verify the field.

<?PHP$user=Array(    ' Name ' = ' spark1985 ', ' email ' = ' [email protected] ', ' mobile ' = ' 13312345678 ');//for general verificationif(Empty($user)) {     die(' User information cannot be empty ');}if(strlen($user[' Name ']) < 6) {     die(' User name is at least 6 bits long ');}//The user name must be a letter, a number, and an underscoreif(!Preg_match('/^\w+$/i ',$user[' Name '])) {     die(' User name is not valid ');}//Verify that the mailbox is formatted correctlyif(!Preg_match('/^[\w\. ') [Email protected]\w+\.\w+$/i ',$user[' Email '])) {     die(' Email is illegal ');}//The phone number must be 11 digits and start with 1if(!Preg_match('/^1\d{10}$/i ',$user[' Mobile '])) {     die(' mobile phone number is not legal ');}Echo' User information verification success ';

PHP Learning-Regular expressions

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.