Regular Expressions in PHP

Source: Internet
Author: User
ArticleDirectory
    • Introduction to regular expressions and the role of regular expressions in PHP
    • Rule match preg_match
    • Rule Replacement preg_replace
    • Rule segmentation preg_split
    • Appendix: PCRE syntax Guide
    • Introduction to regular expressions and the role of regular expressions in PHP
    • Rule match preg_match
    • Rule Replacement preg_replace
    • Rule segmentation preg_split
    • Appendix: PCRE syntax Guide

1. Regular Expressions in PHP
2. Eight practical PHP Regular Expressions
3. How to Write PHP regular expressions that are easier to read
4. Half an hour proficient in Regular Expressions
5. Application of regular expressions in the document collection system and FAQs
6... more planning...

In terms of the source of the article content, some old articles on this site have been reorganized, and some English documents have been translated (thanks for your help in Canada! OEL students). Some of them are personal experiences.
My personal abilities are limited, so there must be some mistakes. Please remind me and correct them. do not mislead new users. if the article can give you some reference, it will be very satisfying. we also welcome PHP fans to contribute and improve this series so that new users can take less detours.


PHP and regular expression series: Regular Expressions in PHP

Introduction to regular expressions and the role of regular expressions in PHP

Regular Expressions are a way to express rules. Using these rules in PHP allows you to flexiblyMatch,Inspection,ReplaceAndModifyString. This article covers the basics of PCRE and how to use the preg_match (), preg_replace (), and preg_split () functions.

Next, let's start from the instance step by step to learn how to use these functions.

Rule match preg_match

With preg_match (), we can complete string rule matching. If a match is found, the preg_match () function returns 1; otherwise, 0. Another optional third parameter allows you to store the matched part in an array. This function can be very useful when verifying data.

$ String = "football ";
If (preg_match ('/Foo/', $ string )){
// The matching is correct.
}

The above example will be matched successfully because the word football contains Foo. Now let's try a more complex one, such as verifying an email address.

$ String = "first.last@domain.uno.dos ";
If (preg_match (
'/^ [^ 0-9] [a-zA-Z0-9 _] + ([.] [a-zA-Z0-9 _] +) * [@] [a-zA-Z0-9 _] + ([.] [a-zA-Z0-9 _] +) * [.] [A-Za-Z] {2, 4} $ /',
$ String )){
// Verify the email address
}

This example verifies that the email address is in the correct format. Now let's take a look at the various rules represented by this regular expression.

PCRE, as its name implies, has the same syntax as the regular expression in Perl, so each regular expression must have a pair of delimiters. We generally use/It is the delimiter.

Starting^And end$Let PHP check from the beginning of the string to the end. If no $,ProgramIt will still match the end of the email.

[And]Used to limit the type of license input. For example, a-Z allows all lowercase letters, A-Z allows all uppercase letters, 0-9 all numbers, and so on, and more other types.

{And}Used to limit the expected number of characters. For example, {2, 4} indicates that each section of a string can contain 2-4 characters, such as .com.cn or. info. Here ,"."It is not a single character, because the licensed input type defined earlier than {2, 4} is only uppercase/lowercase letters, so the segment only matches uppercase/lowercase letters.

(And)Used to merge sections and define characters that must exist in strings. (A | B | C) can match A, B, or C.

(.) Will match all characters, while [.] will only match"..

To use some symbols, you must add . These characters are:() []. *? + ^ | $
Rule Replacement preg_replace

Preg_replace allows you to replace the regular expression that matches your definition in the string. A simple annotation removal function:

Preg_replace ('[(/*) +. + (*/)]', '', $ Val );

This sectionCodeYou can remove multiple comments using/* comments */format in PHP and CSS. The three parameters areRegular Expression, The string to be replaced and the target string to be replaced (here we need to remove the function, so it is a blank string-> ''). If you want to match sub-rules, you can use $0 to represent all matches, $1, $2, and so on.
Rule segmentation preg_split

Preg_split splits the entire string into multiple segments of 1, 2, or more characters according to the matched regular expression. For example, to obtain tags, whether they are separated by spaces or commas:

$ Tags = preg_split ('/[,]/', 'My, tags, venvenly, spaced ');
Print_r ($ tags );

Regular Expressions are a practical technique that allows you to focus on the expected content.

However, it is annoying to have a regular expression that does not give you the expected results, so I will attach some simple grammar guides in the second article of this series to help you.

If you want to skip the painful exercise process and get some success, please look forward to "PHP and regular expression series 2: Eight practical PHP regular expressions" from the PhP5 Research Office ".

Appendix: PCRE syntax Guide

/Delimiters
^String Header
$End of string
[A-Z]All lowercase letters
A-ZAll uppercase letters
[0-9]All numbers
?Zero or a forward character
*Zero or multiple leading characters
+One or more leading characters
{4}Four leading characters
{4, 8}4-8 leading characters
.Any character
(Red | green | blue)Red, green, or blue)
SSpace

Special characters (must be prefixed)

() []. *? + ^ | $

Starting today, we will begin to get a series of articles in the PHP tutorial series, mainly for regular expressions.
The approximate content sorting is arranged as follows:

1. Regular Expressions in PHP
2. Eight practical PHP Regular Expressions
3. How to Write PHP regular expressions that are easier to read
4. Half an hour proficient in Regular Expressions
5. Application of regular expressions in the document collection system and FAQs
6... more planning...

In terms of the source of the article content, some old articles on this site have been reorganized, and some English documents have been translated (thanks for your help in Canada! OEL students). Some of them are personal experiences.
My personal abilities are limited, so there must be some mistakes. Please remind me and correct them. do not mislead new users. if the article can give you some reference, it will be very satisfying. we also welcome PHP fans to contribute and improve this series so that new users can take less detours.


PHP and regular expression series: Regular Expressions in PHP

Introduction to regular expressions and the role of regular expressions in PHP

Regular Expressions are a way to express rules. Using these rules in PHP allows you to flexiblyMatch,Inspection,ReplaceAndModifyString. This article covers the basics of PCRE and how to use the preg_match (), preg_replace (), and preg_split () functions.

Next, let's start from the instance step by step to learn how to use these functions.

Rule match preg_match

With preg_match (), we can complete string rule matching. If a match is found, the preg_match () function returns 1; otherwise, 0. Another optional third parameter allows you to store the matched part in an array. This function can be very useful when verifying data.

$ String = "football ";
If (preg_match ('/Foo/', $ string )){
// The matching is correct.
}

The above example will be matched successfully because the word football contains Foo. Now let's try a more complex one, such as verifying an email address.

$ String = "first.last@domain.uno.dos ";
If (preg_match (
'/^ [^ 0-9] [a-zA-Z0-9 _] + ([.] [a-zA-Z0-9 _] +) * [@] [a-zA-Z0-9 _] + ([.] [a-zA-Z0-9 _] +) * [.] [A-Za-Z] {2, 4} $ /',
$ String )){
// Verify the email address
}

This example verifies that the email address is in the correct format. Now let's take a look at the various rules represented by this regular expression.

PCRE, as its name implies, has the same syntax as the regular expression in Perl, so each regular expression must have a pair of delimiters. We generally use/It is the delimiter.

Starting^And end$Let PHP check from the beginning of the string to the end. If there is no $, the program will still match to the end of the email.

[And]Used to limit the type of license input. For example, a-Z allows all lowercase letters, A-Z allows all uppercase letters, 0-9 all numbers, and so on, and more other types.

{And}Used to limit the expected number of characters. For example, {2, 4} indicates that each section of a string can contain 2-4 characters, such as .com.cn or. info. Here ,"."It is not a single character, because the licensed input type defined earlier than {2, 4} is only uppercase/lowercase letters, so the segment only matches uppercase/lowercase letters.

(And)Used to merge sections and define characters that must exist in strings. (A | B | C) can match A, B, or C.

(.) Will match all characters, while [.] will only match"..

To use some symbols, you must add. These characters are:() []. *? + ^ | $
Rule Replacement preg_replace

Preg_replace allows you to replace the regular expression that matches your definition in the string. A simple annotation removal function:

Preg_replace ('[(/*) +. + (*/)]', '', $ Val );

This code can remove multiple comments using/* comments */format in PHP and CSS. The three parameters areRegular Expression, The string to be replaced and the target string to be replaced (here we need to remove the function, so it is a blank string-> ''). If you want to match sub-rules, you can use $0 to represent all matches, $1, $2, and so on.
Rule segmentation preg_split

Preg_split splits the entire string into multiple segments of 1, 2, or more characters according to the matched regular expression. For example, to obtain tags, whether they are separated by spaces or commas:

$ Tags = preg_split ('/[,]/', 'My, tags, venvenly, spaced ');
Print_r ($ tags );

Regular Expressions are a practical technique that allows you to focus on the expected content.

However, it is annoying to have a regular expression that does not give you the expected results, so I will attach some simple grammar guides in the second article of this series to help you.

If you want to skip the painful exercise process and get some success, please look forward to "PHP and regular expression series 2: Eight practical PHP regular expressions" from the PhP5 Research Office ".

Appendix: PCRE syntax Guide

/Delimiters
^String Header
$End of string
[A-Z]All lowercase letters
A-ZAll uppercase letters
[0-9]All numbers
?Zero or a forward character
*Zero or multiple leading characters
+One or more leading characters
{4}Four leading characters
{4, 8}4-8 leading characters
.Any character
(Red | green | blue)Red, green, or blue)
SSpace

Special characters (must be prefixed)

() []. *? + ^ | $

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.