The most understandable tutorials for PHP regular expressions

Source: Internet
Author: User
Tags foreach character classes ereg function prototype html tags pear php regular expression trim

Basic knowledge

POSIX Extended Regular Expression functions
Perl-compatible Regular expression functions
From the message verification.

The format of the message:

Where Tenssun is the user name, is the server name

The user name can only be composed of an English letter a~z (case-insensitive), a digital 0~9, and an underscore.

The starting character of the username must be an English letter. such as: netease_2005

User name length is 5~20 characters.

The server name can only be made up of English letter a~z (case-insensitive), numeric 0~9, underscores, and points, and the length after the @ point is limited to 1-10 characters, followed by a limit of com,cn,,net.


$email = ' ';
if (Ereg ("^[a-za-z][0-9a-za-z_]{4,19}@[0-9a-za-z_]{1,10} (\.) (com|cn||net) $ ", $email)) {
Echo ' email format is correct ';
^ and $
See the previous message validation most people may feel a headache, don't worry, let's slow down.

Still have to say ^ and $ they are used to match the start and end of the string separately, the following method illustrates:

"^the": The beginning must have "the" string;

"Of despair$": The end must have a string of "of despair"; So

"^abc$": a string that requires the beginning of ABC and the end of ABC, which is actually only an ABC match

"Notice": matches a string containing notice you can see if you're not using the two characters we mentioned (the last example), which means that the pattern (regular expression) can appear anywhere in the checked string, you don't lock him on either side (start or end)

' * ', ' + ', and '? ',

Then, say ' * ', ' + ', and '? ', they are used to indicate the number of times a character can appear or order. They said separately:

* indicates that 0 or 1 times or more than {0},

+ indicates that 1 or more times is equal to {1,},

? Represents 0 or 1 times the equivalent of {0,1}, here are some examples:

"ab*": and Ab{0,} synonymous, matching with a start, followed by 0 or n B of the string ("a", "AB", "abbb", etc.);
"ab+": and Ab{1,} synonymous with the same as above, but at least one B exists ("AB", "abbb", etc.);
"AB": Synonymous with ab{0,1}, can be without or only a B;
"a?b+$": a string that matches the end of one or 0 a plus more than one B.
Main points: ' * ', ' + ', and '? ' Just the character in front of it.

{ }

You can also limit the number of characters appearing in curly braces, such as

"Ah{2}": Require a must be followed by two H (one also can not be less) ("ahh");
"Ah{2,}": Require a must have two or more than two H (such as "ahh", "ahhhh", etc.);
' ah{3,5} ': Requires that a 3-5 h ("Ahhh", "Ahhhh", or "ahhhhh") be followed by a.
() {}

Now we have to put a few characters in parentheses, such as:

"A (BC) *": Match a followed by 0 or more "BC";
"A (BC) {1,5}": one to 5 "BC."

There is also a character ' │ ' that corresponds to an or (or) operation:

"Hi│hello": matches a string containing "hi" or "hello";
"(B│CD) EF": Matches a string containing "bef" or "cdef";
"(a│b) *c": matches a string containing such multiple (including 0) A or B, followed by a C;

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

What if you want to match all the individual characters, including "\ n"?

with ' [\ n.] ' This pattern.

"A.[0-9]": A plus one character plus a number 0 to 9

". {3}$: Three any character end.

[ ]

The content enclosed in brackets matches only one single character

"[AB]": Match a single A or B (as with "a│b");

[a-d]: a single character that matches ' a ' to ' d ' (same as ' a│b│c│d ' and ' [ABCD] ' effect); Generally we use [a-za-z] to specify characters for a single case of English

' ^[a-za-z] ': matches a string that starts with the uppercase and lowercase letters

' [0-9]% ': matches a string containing x-percent

", [a-za-z0-9]$": matches a string that ends with a comma plus a number or letter

The difference between ^[] and [^]

You can also put you don't want to get the character column in brackets, you just need to use ' ^ ' in the parentheses as the opening "%[^a-za-z]%" match contains two percent signs inside a non-alphanumeric string.

Important: ^ With the beginning of brackets, it means excluding the characters in parentheses.

Don't forget that the characters inside the brackets are exceptions to this rule road-inside the brackets, all the special characters, including ('), will lose their special properties "[*\+?{}.]" Matches a string containing these characters.

{} \b

Looking at the example above, you should understand {n,m}. Note that N and m cannot be negative integers, and that n is always less than M. In this way, you can match at least N times and match up to M times. such as "p{1,5}" will match the first five p in "PVPPPPPP"

Let's talk about the beginning of the

\b said he was used to match a word boundary, which is ... such as ' ve\b ', can match the love of VE and do not match very have ve

\b is exactly the opposite of the \b above. I'm not going to give you an example.

Application of a

Okay, so much to say. Let's go back and see how our emails are structured:

Regular expressions for user names


A-Z represents all lowercase letters A through Z, A-Z represents all uppercase letters A through Z, but [] can only take one character, so [a-za-z] can only take one of the characters, that is, only one letter from all uppercase and lowercase letters, ^ placed outside [] to start, so ^[a-za-z] The expression begins with an English letter.

Application of two

[0-9a-za-z_] means to take one character from all Arabic numerals and English and _, while {4,19} matches at least 4 times, up to 9 times it is obvious

[0-9a-za-z_] {4,19} indicates that the preceding character appears at least 4 times, up to 19 times.

So, now, what's the meaning of the expression below?


(\.) Represents a point and '. ' Confuse the '. ' Is any of the characters except \ n () indicating that this is a child-master

(com|cn||net) $

Represents a string of characters at the end of COM or CN or or net

Introduction of regular expressions

A regular expression is a grammatical rule used to describe a character arrangement pattern. It is mainly used for pattern segmentation, matching, lookup and substitution operations of strings. So far, the exact (text) match we used earlier is also a regular expression.

In PHP, regular expressions are generally a procedural description of a text pattern composed of regular characters and some special characters (similar to wildcards).

In a programming language, you typically include a pattern expression (that is, a regular expression) between two backslashes "/", such as "/apple/". Users need to match the pattern of the content into the delimitation between the.

If you use a regular expression that has no special characters, which is equivalent to a plain text search, the same effect can be achieved by using the STRSTR () function.

There are two sets of regular expression libraries in PHP that are similar in functionality, but have slightly different execution efficiencies:

A set is provided by the Pcre (Perl compatible Regular Expression) library. A function named after a prefix using "preg_";
One set is provided by the POSIX (Portable Operation System interface) extension. Use a function named "Ereg_" as a prefix;
One of the reasons for using regular expressions is that in a typical search and replace operation, only the exact text can be matched, and the search for the object's dynamic text is difficult or even impossible.

/^[0-9a-za-z_-]+@[0-9a-za-z_-]+ (\.[ 0-9a-za-z_-]+) {0,3}]$/
The more important and useful role of regular expressions is to validate the validity checks of user data. In PHP, regular expressions have three effects:

Match, and is often used to extract information from a string.
Replaces the matching text with the new text.
Splits a string into a smaller set of pieces of information.
Syntax rules for regular expressions

Regular expressions are mainly composed of:

Atoms (ordinary character, such as English characters)
Metacharacters (characters with special functions)
As well as the pattern modifier character composition.
Contains at least one atom in a regular expression.

Atom (Atom)

Atoms are the basic units that make up regular expressions, which should be used as a whole when analyzing regular expressions.

Atomic characters are made up of print and nonprinting characters that are all explicitly specified as metacharacters. This includes all the English letters, numbers, punctuation marks, and other symbols. Atoms also include the following elements.

A single character, number, such as a~z,a~z,0~9.
A pattern unit, such as (ABC), that can be understood as a large atom composed of multiple atoms.
Atomic tables, such as [ABC].
The mode unit that is reused.
The normal escape character.
The escape meta character.
Normal escape characters used by regular expressions

Atomic description
\d match a number; equivalent to [0-9]
\d matches any character except a number; equivalent to [^0-9]
\w match an English letter, number, or underscore; equivalent to [0-9a-za-z_]
\w matches any character except English letters, numbers, and underscores; equivalent to [^0-9a-za-z_]
\s match a blank character; equivalent to [\f\n\r\t\v]
\s matches any one character except whitespace; equivalent to [^\f\n\r\t\v]
\f matches a page feed character equivalent to \x0c or \CL
\ n matches a newline character, equivalent to \x0a or \CJ
\ r matches a carriage return equivalent to \x0d or \cm
\ t matches a tab character, equivalent to \x09\ or \CL
\v matches a vertical tab; equivalent to \x0b or \ck
\onn match a octal number
\XNN matches a hexadecimal digit
\CC matches a control character
Metacharacters (Meta-character)

A metacharacters is a character that is used to construct a regular expression with special meaning. If you want to include the metacharacters themselves in a regular expression, you must precede it with "\" to escape

Description Meta character
* 0 times, 1 times or more to match the atoms before them
+ 1 or more times to match the atoms before it
? 0 times or 1 times to match the atoms before them
. Match any one character
| Match two or more selections
^ or \a an atom that matches the head of string strings
$ or \z the atoms that match the tail of string strings
\b Matches the bounds of a word
\b Matches parts other than word boundaries
[] matches any atom in square brackets
[^] matches any character except the atom in square brackets
() The whole represents an atom
{m} indicates that the former atom appears just as M times
{M,n} indicates that its front atom appears at least m times, at most n times (n>m)
{m,} indicates that its front atom appears not less than M-atom table
The atomic table "[]" holds a group of atoms that are equal in status and match only one of the atoms. If you want to match a "a" or "E" use/[ae]/, for example:/pr[ae]y/match "Pray" or "prey".
The atomic table "^" or the excluded atomic table, matches any character except the atoms in the table. For example:/p[^u]/matches "Pa" in "part", but cannot match "Pu" in "Computer" because "U" is excluded in the match.
Typically, in an atomic table, "-" joins a set of atoms arranged in ASCII order to simplify writing. such as/x[0123456789] can be written as/x[0-9]/to match a string composed of "X" letters and a number;
/0[xx][0-9a-fa-f]/matches a simple hexadecimal number, such as "0x9". /[^0-9a-za-z_]/matches any character except English letters, numbers, and underscores, which is equivalent to/\w/.
Duplicate match

There are some metacharacters in the regular expression that are used to duplicate the previous atoms: "?", "*", "+". Their main difference is that the number of duplicate matches is different.

Meta character "? "represents 0 or 1 matches of atoms immediately preceding them." For example:/colou?r/matches "colour" or "color".
The metacharacters "*" Represent 0, 1, or more times to match the atoms immediately preceding them. For example:/^<[a-za-z][a-za-z0-9]*>$/can match HTML tags such as "<P>", "The metacharacters "+" represents 1 or more times to match the atoms immediately preceding them. For example:/go+gle/matches "Gogle", "Google", or "Gooogle" with a string containing multiple o in the middle. The example of the hexadecimal number mentioned above is actually a more perfect match expression is/^0? [XX] [0-9a-fa-f]+$/, can match "0x9b3c" or "X800" and so on.
To accurately specify the number of times an atom repeats, you can also use the metacharacters "{}" to specify the number of occurrences of the matched atom. "{m}" means that the former atom appears exactly m times; "{M,n}" indicates that its former atom appears at least m times, at most n times, and "{m,}" indicates that its former atom appears not less than m times.

Here are some examples.

/zo{1,3}m/can only match the string "Zom", "Zoom", or "zooom".
/zo{3}m/can only match string "Zooom"
/zo{3,}m/can match a string that starts with "Z" and ends with "m" at least 3 "O" in the middle.
/bo{0,1}u/can match the "Bou" and "Bu" in the string "bought a butter", which is completely equivalent to/bo?u/.
Boundary restrictions

In some cases, the matching scope needs to be qualified for more accurate matching results.

The meta character "^" (or "\a") is placed at the beginning of the string to ensure that the pattern match appears at the first end of the string;

"$" (or "\z") is placed at the end of the string, ensuring that pattern matching appears at the end of the string.

For example, "Tom" in the string "Tom and Jerry chased each of the until Tom's uncel come in" with the/^tom or Atom match at the beginning of the sentence, and/in$ or/in\z matches the end of the sentence "Co ' In ' in ' Me in '. If you do not add bounds to the metacharacters, you will get more matching results.

When you use the lookup features of various editing software, you can get more accurate results by selecting "Find by word". Similar functionality is provided in regular expressions.

The meta character "\b" matches the boundary of the word;

"\b" matches the inside of a word.

For example, using/\bis\b/in the string "This island be a beautiful land" can match the word "is" and is independent of "this" or "island". /\bis/matches the word boundary, you can match the ' is ' in the word ' is ' and ' island ';/\bis/does not match the left edge of the word and can match the ' is ' in the word ' is ' and ' this './\bis\b will explicitly indicate that it does not match the left and right edges of the word, Matches only the inside of a word. So there is no result in this example.

Meta character "."

Meta character "." Matches any character other than a newline character, equivalent to [^\n] (Unix system) or [^\r\n] (Windows system).

For example:/pr.y/can match the string "prey", "Pray" or "pr%y", and so on.

You can usually use a combination of ". *" to match any character except for a newline character. In some books it is also called a "full match" or a "single containing match."

For example, a/a.*z/representation can match the beginning of the letter "a", and any string that does not include line breaks at the end of the letter "Z". ". +" can also accomplish a similar matching function, which is different in that it matches at least one character. For example,/a.+z/will not match the string "AZ".

Pattern Selector

Meta character "|" Also known as the pattern selector. Matches one of two or more selections in a regular expression.

For example:

In the string "There are many apples and pears." ,/apple|pear/matches "Apple" at the first run, and matches "pear" when it is run again. You can also continue to add options, such as/apple|pear|banana|lemon/.

Pattern Unit

The meta character "()" converts a regular expression into an atom (or modal unit). Similar to the parentheses in a mathematical expression, "()" can be used as a single unit.

For example:

/(DOG) +/matching "Dog", "Dogdog", "Dogdogdog" ... because the atom before "+" is the string "Dog" enclosed by the Metacharacters "()".

An expression in a pattern cell will be given a priority match or operation. The system automatically stores the matching of these pattern units in sequence, and can be referenced in the form of "\1", "\2" and "\3" when needed. This approach is very easy to manage when a regular expression contains the same pattern unit.

For example:

/^\d{2} ([\w]) \d{2}\\1\d{4}$ matches strings such as "12-31-2006", "09/27/1996", "86 01 4321". However, these regular expressions do not match the format of "12/34-5678". This is because the result "/" of the Mode "[\w]" has been stored. The match pattern is also the character "/" when the next position "\1" is referenced.

mode modifier (Pattern modifiers)

Pattern modifiers extend some of the functionality of regular expressions in character matching and substitution operations. These extensions, or corrections, enhance the processing power of regular expressions. Pattern modifiers are generally marked outside the entire pattern and can be combined, such as "/apple/i", "/cat|dog/uis", and so on. The table lists some of the most commonly used pattern modifiers for extremely functional descriptions.

Pattern modifier Description
I can match uppercase and lowercase letters at the same time
M treats a string as multiple lines
S treats a string as a single line, and a newline character treats as a normal
White space in x mode is negligible
S when a pattern is used several times, it is worthwhile to analyze it for the sake of accelerated matching
U match to the nearest string
E uses the substituted string as an expression
Here are a few simple examples to illustrate the use of pattern modifiers

/apple/i matches "Apple" or "apple" and so on, ignoring case.

/I love You/ix matches "IloveYou", ignoring case and whitespace.

/<.*>/u will sequentially match the string "<b>Cool</b> music


Character classes for POSIX-style regular expressions:

[[: Alnum:]] Text number character
[[: Alpha:]] alphabetic characters
[[: Lower:]] Small Letter
[[: Upper:]] Capital letters
[[:d Igit:]] Decimal
[[: Xdigit:]] hexadecimal digits
[[:p UNCT:]] Punctuation
[[: Blank:]] tabs and spaces
[[: Space:]] whitespace characters
[[: Cntrl:]] Control
Regular expression functions in PHP

In PHP There are two sets of regular expression libraries.

A set is provided by the Pcre (Perl compatible Regular Expression) library. The Pcre library implements pattern matching for regular expressions using the same syntax rules as Perl, using functions named "Preg_" as prefixes.
The other is provided by the POSIX (Portable Operation System Interface) extension Library. POSIX-extended regular expressions are defined by POSIX 1003.2 and typically use functions named "Ereg_" as prefixes.
The functions of the two sets of functions are similar and the execution efficiency is slightly different. In general, to achieve the same functionality, the use of the Pcre library has a slightly more efficient advantage.

Matching of regular expressions

1, Preg_match () function

Function prototype:

int Preg_match (string $pattern, String $content [, array $matches])
The Preg_match () function searches the $content string for content that matches the regular expression given by $pattern. If $matches is provided, the matching result is placed in it. $matches [0] will contain the entire matching text, $matches [1] will contain the first captured content that matches the pattern unit in parentheses, and so on. The function only makes one match, and eventually returns the number of matches of 0 or 1.

A matching string is required. The DATE function returns the current time
$content = "Current date and". Date ("y-m-d h:i a"). ", we are learning PHP together.";

Use the usual method to match the time
if (Preg_match ("/\d{4}-\d{2}-\d{2} \d{2}:\d{2} [ap]m/", $content, $m))
echo "matches the time:". $m [0]. "\ n";

Because of the pattern of time is obvious, can also simple match
if (Preg_match ([\d-]{10}) ([\d:]{5} [Ap]m)/", $content, $m))
echo "Current date is:". $m [1]. "\ n";
echo "Current time is:". $m [2]. "\ n";
2, Ereg () and eregi ()

Ereg () is a matching function of a POSIX-extended regular expression. Eregi () is a version of the ignored size of the ereg () function. Both are similar to the Preg_match function, but the function returns a Boolean value indicating whether the match was successful or not. It is to be explained that the first parameter of the POSIX extension library function accepts the regular expression string, that is, no use of the factorization character is required.

Typically, using Perl-compatible regular expression matching functions perg_match () will be faster than using Ereg () or eregi (). If you are simply looking for a string that contains a substring, it is recommended that you use the STRSTR () or Strpos () function.

$username = $_server[' Remote_user '];
$filename = $_get[' file '];

Filter file names to ensure system security
if (!ereg (' ^[^./][^/]*$ ', $userfile))
Die (' This is an illegal filename! ');

Filter the user name
if (!ereg (' ^[^./][^/]*$ ', $username))
Die (' This is not a valid username ');

Flatten file paths through security filtering
$thefile = "/home/$username/$filename";
3, Preg_grep ()

Function Prototypes:

Array Preg_grep (string $pattern, array $input)
The Preg_grep () function returns an array that includes the cells in the $input array that match the given $pattern pattern. For each element in the input array $input, Preg_grep () is matched only once.

$subjects = Array (
"Mechanical Engineering", "Medicine",
"Social Science", "agriculture",
"Commercial Science", "politics"

Match all account names that consist of only one word
$alonewords = Preg_grep ("/^[a-z]*$/i", $subjects);
Make a global regular expression match
1, Preg_match_all ()

Similar to the Preg_match () function. If the third argument is used, all possible matches are put into. This function returns the number of times the entire pattern match (possibly 0), if error returns false.

Function: Convert the link address in text to HTML
Input: String
Output: String
function url2html ($text)
Match a URL until there is a blank
Preg_match_all ("/http:\/\/?[ ^\s]+/i ", $text, $links);

Set the length of the page to display the URL address
$max _size = 40;
foreach ($links [0] as $link _url)
Calculates the length of the URL. If the $max_size setting is exceeded, it is shortened.
$len = strlen ($link _url);

if ($len > $max _size)
$link _text = substr ($link _url, 0, $max _size). " ...";
} else {
$link _text = $link _url;

Generate HTML text
$text = Str_replace ($link _url, "<a href= ' $link _url ' > $link _text</a>", $text);
return $text;

Run instance
$str = "This is a multiline text that contains multiple URL link addresses. Welcome to visit ";
Print url2html ($STR);

/* Output Results
This is a multiline text that contains multiple URL link addresses. Welcome to <a href= ' ' >
Multiple-line matching
Only using POSIX regular expression functions, it is difficult to perform complex matching operations. For example, a matching lookup is made for an entire file, especially multiple lines of text. One way to do this with Ereg () is by branch processing.

$rows = File (' php.ini '); Read the php.ini file to the array

Circulation calendar
foreach ($rows as $line)
If (Trim ($line))
Writes the parameters that match successfully to the array
if (eregi ("^ [a-z0-9_.] *) *= (. *) ", $line, $matches))
$options [$matches [1]] = Trim ($matches [2]);
Unset ($matches);

Output parameter Results
Print_r ($options);
Replacement of regular expressions

1, Ereg_replace () and Eregi_replace ()

Function prototype:

String Ereg_replace (String $pattern, String $replacement, String $string)
String Eregi_replace (String $pattern, String $replacerment, String $string)
Ereg_replace () Searches for the pattern string $pattern in $string and replaces the matched result with $sreplacement.

When the $pattern contains a modal unit (or child mode), the positions in the $replacement, such as "\1" or "$", are replaced in turn by the content matched by those child patterns. and "Yes" or "$" is the content of only the entire matching string. It is important to note that in double quotes the backslash is used as an escape character, so you must use the "\\0", the \\1 form.

Eregi_replace () and ereg_replace () have the same functionality, except that the former ignores case

$lines = File (' source.php '); Reading a file into an array

for ($i =0; $i <count ($lines); $i + +)
Remove a comment that starts at the end of the line with "\" or "#"
$lines [$i] = Eregi_replace ("(\/\/|#). *$", "", $lines [$i]);
Eliminate the white space at the end of the line
$lines [$i] = Eregi_replace ("[\n\r\t\v\f]*$", "\ r \ n", $lines [$i]);

Output to page after finishing
Echo Htmlspecialchars (Join ("", $lines));
2, Preg_replace ()

Function prototype:

Mixed preg_replace (mixed $patten, mixed $replacement, mixed $subject [, int $limit])
Preg_replace is more powerful than Ereg_replace, the first three parameters can use an array, the fourth argument $limit can set the number of substitutions, default to replace All.

$string = "Name: {name}<br>\nemail: {email}<br>\naddress: {address}<br>\n";

$patterns =array (

Replace string
$replacements = Array (
"No.5, Wilson St., New York, U.S.A",
"Thomas Ching",

Output mode substitution results
Print Preg_replace ($patterns, $replacements, $string);
Split of regular expressions
1. Split () and Spliti ()

Function Prototypes:

Array split (string $pattern, string $string [, int $limit])
This function returns an array of strings, each of which is a substring separated by a regular expression $pattern as a boundary $string. If $limit is set, the returned array contains a maximum of $limit cells. And the last of these cells contains all the remaining parts of the $string. Spliti is a split, ignore size version.

$date = "08/30/2006";

The delimiter can be a slash, a dot, or a horizontal line
List ($month, $day, $year) = Split (' [/.-] ', $date);

Output to another time format
echo "Month: $month; Day: $day; Year: $year <br/>\n ";
2, Preg_split ()

This function is consistent with the function of the split function.

$seek = Array ();
$text = "I have a dream" I can make it. So just does it, nothing is impossible! ";

Blank the string, punctuation marks (you may also have spaces after each punctuation)
$words = Preg_split ("/[.,;! \s ']\s*/', $text);
foreach ($words as $val)
$seek [Strtolower ($val)] + +;

echo "Total approximately". Count ($words). "A word. ";
echo "in common". $seek [' I ']. "The word" I ". ";
Application of Wed verification for regular expressions
Verification of e-mail addresses

/* Verify Email address * *
function Checkmail ($email)
User name, by "\w" format character, "-" or "." Composition
$email _name = "\w| (\w[-.\w]*\w) ";

The first paragraph in the domain name is similar to the rule and user name, excluding the dot number "."
$code _at = "@";
$per _domain = "\w| (\w[-\w]*\w) ";

The middle part of the domain, up to two paragraphs
$mid _domain = "(\.") $per _domain. ") {0,2}";

The last paragraph in the domain name can only be ". com", ". org", or ". NET"
$end _domain = "( com|net|org)) ";

$rs = Preg_match (
"/^{$email _name}@{$per _domain}{$mid _domain}{$end _domain}$/",
return (bool) $rs;

Test, return success below
Var_dump (Checkmail ("root@localhost"));
Var_dump (Checkmail (""));
Var_dump (Checkmail (""));
Verification of URL addresses

/* Verify URL Address * *
function Checkdomain ($domain)
Return Ereg ("^ (HTTP|FTP) s?:/ /(www\.)? + (com|net|org) $ ", $domain);

$rs = Checkdomain (""); return False
$rs = Checkdomain (""); return True
Phone number

/* Check Phone number *
function Checktelno ($tel)
Remove the extra separator
$tel = ereg_replace ("[\ \] \. -] "," ", $tel);

Contains only numbers, at least one 6-bit phone number (that is, no area code)
if (Ereg ("^\d+$", $tel))
return true;
return false;

$rs = Checktelno ("(086)-0411-12345678"); return True
Check of postal code

/* Check ZIP/Postal code *
function Checkzipcode ($code)
Remove the extra separator
$code = Preg_replace ("/[\.") -]/"," ", $code);

Contains a 6-bit ZIP code
if (Preg_match ("/^\d{6}$/", $code))
return true;
return false;

$rs = Checkzipcode ("123456"); return True
At this point, the most understandable php regular expression tutorial ends!

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: 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.