Php regular expression quick start (2)

Source: Internet
Author: User
Tags ereg
Many may have headaches for regular expressions. Today, I want to use the expressions that ordinary people can understand with my understanding and some online articles. Share your learning experience with you.

Many may have headaches for regular expressions. Today, I want to use the expressions that ordinary people can understand with my understanding and some online articles. Share your learning experience with you.

The beginning is still worth mentioning ^ and $ are used to match the start and end of the string respectively. The following are examples:

"^ The": must start with a "The" string;
"Of despair $": the end must contain a "of despair" string;

So,
"^ Abc $": a string that must start with abc and end with abc. In fact, only abc matches;
"Notice": matches the string containing the notice;

You can see that if you do not use the two characters we mentioned (the last example), that is, the pattern (regular expression) can appear anywhere in the string to be tested, you didn't lock him to either side.

Next, let's talk about '*' + 'and '? '
They are used to indicate the number or order of occurrences of a character. they represent:
"Zero or more" is equivalent to {0 ,}
"One or more" is equivalent to {1 ,}
"Zero or one." is equivalent to {0, 1}

Here are some examples:

"AB *": it is synonymous with AB {0,}. it matches a string starting with a and followed by 0 or N B ("a", "AB ", "abbb", etc );
"AB +": it is synonymous with AB {1,}. it is the same as the above, but at least one B must exist ("AB" and "abbb );
"AB ?" : It is synonymous with AB {0, 1} and can have no or only one B;
"? B + $ ": match a string that ends with one or zero a plus more than one B.

Key points: '*' + 'and '? 'Only the character before it.

You can also limit the number of characters in braces, for example:

"AB {2}": requires that a be followed by two B (one cannot be less) ("abb ");
"AB {2,}": requires that there must be two or more B (such as "abb" and "abbbb") after );
"AB {3, 5}": requires that a can be followed by 2 to 5 B ("abbb", "abbbb", or "abbbbb ").

Now we can put a few characters in parentheses, for example:

"A (bc) *": matches 0 or a "bc" after ";
"A (bc) {}": one to five "bc ";

There is also a character '|', which is equivalent to the OR operation:

"Hi | hello": matches strings containing "hi" or "hello;
"(B | cd) ef": matches strings containing "bef" or "cdef;
"(A | B) * c": matches strings containing multiple (including 0) a or B, followed by a string of c;

A point ('.') can represent all single characters, excluding "\ n"

What if we want to match all single characters including "\ n?

Use the '[\ n.]' mode.

"A. [0-9]": add a character to a pair and a number ranging from 0 to 9;
"^. {3} $": the end of any three characters.

The content enclosed in brackets only matches a single character.

"[AB]": Matches a or B (the same as "a │ B );
"[A-d]": matches a single character from 'A' to 'D' (same as "a │ B │ c │ d" and "[abcd );

Generally, we use [a-zA-Z] to specify a character as a case:

"^ [A-zA-Z]": matches a string starting with an uppercase/lowercase letter;
"[0-9] %": matches a string containing an x % character;
', [A-zA-Z0-9] $': match a string that ends with a comma plus a number or a letter;

You can also include characters you don't want in brackets, you only need to use '^' in the brackets to start with "% [^ a-zA-Z] %" to match a non-letter string containing two percentage signs.

Key point: ^ when used at the beginning of the brackets, it indicates that the characters in the brackets are excluded.

For PHP to be able to interpret, you must add "before these characters and escape some characters.

Do not forget that the character in the brackets is an exception to this rule-in the brackets, all the special characters, including ("), all will lose their special nature "[* \ +? {}.] "Matches strings containing these characters:

Also, as the regx manual tells us: "If the list contains ']', it is best to use it as the first character in the list (probably after '^ ). If it contains '-', it is better to put it in front or at the end, or in the middle of the second end point of a range [a-d-0-9] '-' will be valid.

After reading the example above, you should understand {n, m. Note that n and m cannot be negative integers, and n is always less than m. In this way, you can match at least n times and at most m times. For example, "p {}" matches the first five p in "pvpppp ".

# P # Paging Title # e #

Which of the following statements start \?

\ B indicates that it is used to match a word boundary, that is... For example, 've \ B 'can match the ve in love instead of very.

\ B is the opposite of \ B above. I will not give it an example.

..... Suddenly remembered .... You can look at the http://www.phpv.net/article.php/251 to see other syntaxes starting \

Well, let's make an application: how to build a pattern to match the number of currency input.

Construct a matching pattern to check whether the input information is a number that represents money. We think there are four ways to indicate the amount of money: "10000.00" and "10,000.00", or there is no fractional part, "10000" and "10,000 ″. Now let's start building this matching mode:

^ [1-9] [0-9] * $

This variable must start with a number other than 0. But this also means that a single "0" cannot pass the test. The solution is as follows:

^ (0 | [1-9] [0-9] *) $

"Only numbers starting with 0 and not starting with 0 match", we can also allow a negative number before the number:

^ (0 | -? [1-9] [0-9] *) $

This is: 0 or a number that starts with 0 and may have a negative number in front. Now let's not be so rigorous. we can start with 0. Now let's give up the negative number, because we don't need to use it to represent coins. We now specify a pattern to match the fractional part:

^ [0-9] + (\. [0-9] + )? $

This implies that the matched string must start with at least one Arabic number. However, note that "10." does not match in the above mode. only "10" and "10.2" can be used. do you know why?

^ [0-9] + (\. [0-9] {2 })? $

We specify that there must be two decimal places after the decimal point. If you think this is too harsh, you can change it:

^ [0-9] + (\. [0-9] {1, 2 })? $

This will allow one to two decimal places. Now we add a comma (every three digits) to increase readability, which can be expressed as follows:

^ [0-9] {1, 3} (, [0-9] {3}) * (\. [0-9] {1, 2 })? $

Do not forget that '+' can be replaced by '*'. if you want to allow blank strings to be input, also, do not forget that the backslashes '\' may cause errors in php strings (common errors ):

Now we can confirm the string. now we can remove all the commas (,) from str_replace (",", "", $ money) then we can regard the type as double, and then we can use it for mathematical computation.

Next:

Construct a regular expression for checking email

There are three parts in a complete email address:

1. username (everything on the left)
2 .'@'
3. server name (that is, the remaining part)

The username can contain uppercase and lowercase letters, Arabic numerals, periods ('.'), periods ('-'), and underscores '_'). The server name also complies with this rule, except for underlines.

The start and end of the user name cannot be a period, and the server does the same. You cannot have at least one character between two consecutive periods. now let's take a look at how to write a matching pattern for the user name:

^ [_ A-zA-Z0-9-] + $

Currently, periods cannot exist. We add:

^ [_ A-zA-Z0-9-] + (\. [_ a-zA-Z0-9-] +) * $

It means that at least one canonicalized character (except.) starts with 0 or more strings starting with a vertex.

To simplify it, we can use eregi () to replace ereg () and eregi () to be case insensitive, we don't need to specify the two ranges "a-z" and "A-Z". you just need to specify one:

^ [_ A-z0-9-] + (\. [_ a-z0-9-] +) * $

The server name is the same, but the underline should be removed:

^ [A-z0-9-] + (\. [a-z0-9-] +) * $

Okay. Now you only need to connect the two parts:

^ [_ A-z0-9-] + (\. [_ a-z0-9-] +) * @ [a-z0-9-] + (\. [a-z0-9-] +) * $

This is the complete email authentication matching mode. you only need to call:

Eregi ("^ [_ a-z0-9-] + (\. [_ a-z0-9-] +) * @ [a-z0-9-] + (\. [a-z0-9-] +) * $ ", $ eamil)

Then you can check whether the email is used.

# P # Paging Title # e #

Other regular expressions

Extract string

Ereg () and eregi () has a feature that allows users to extract part of a string using regular expressions (you can read the manual for specific usage ). For example, if we want to extract the file name from path/URL, the following code is required:

Ereg ("([^ \/] *) $", $ pathOrUrl, $ regs );
Echo $ regs [1];

Advanced replacement

Ereg_replace () and eregi_replace () are also very useful. if we want to replace all the negative signs at intervals with commas:

Ereg_replace ("[\ n \ r \ t] +", ",", trim ($ str ));

Finally, let me analyze another string of regular expressions used to check the EMAIL:

"^ [-! # $ % & \ '* + \./0-9 =? A-Z ^ _ 'a-z {|} ~] + '.'@'.'[-! # $ % & \ '* + \/0-9 =? A-Z ^ _ 'a-z {|} ~] + \.'.'[-! # $ % & \ '* + \./0-9 =? A-Z ^ _ 'a-z {|} ~] + $"

If it is easy to understand, the purpose of this article is achieved.

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.