Summary and Analysis of php regular expression processing functions

Source: Internet
Author: User
Tags php regular expression
The following describes common function codes in php to help you learn php regular expressions preg_grep.
(PHP 4, PHP 5)

Preg_grep -- returns the array unit that matches the pattern.
Description
Array preg_grep (string pattern, array input [, int flags])


Preg_grep () returns an array containing the units in the input array that match the given pattern.

Flags can be the following mark:


PREG_GREP_INVERT
If this flag is passed, preg_grep () returns the units that do not match the given pattern in the input array. This tag is available since PHP 4.2.0.


Starting from PHP 4.0.4, the results returned by preg_grep () are indexed using the key names from the input array. If you do not want such a result, use array_values () to re-index the result returned by preg_grep.

The above is a description of preg_grep () in the manual. First of all, this is a perl-compatible regular function, so I guess preg_grep means p (perl) reg (regular) _ grep. it features can be used as an array and expanded by itself, it can be used for regular expression matching in multi-dimensional arrays, and the flags parameter can be used to return matching or non-matching arrays. The efficiency is much faster than using the foreach (...) {if...} structure (unverified) and can match the complex pattern. It is used in search, inspection, and other applications.

Example:

$ Arr = array ('ABC' => 12.213, 'BB '=> 12345, 'ba' => 23.2321, 34.3, '23' => '3. 3', '000000' => 'BBB ');

// Return all array elements containing floating point numbers.
$ Fl_array = preg_grep ("/^ (\ d + )? \. \ D + $/", $ arr );
Print_r ($ fl_array );

?>

Preg_match
(PHP 3> = 3.0.9, PHP 4, PHP 5)

Preg_match -- Regular Expression Matching
Description
Int preg_match (string pattern, string subject [, array matches [, int flags])


Search for the content that matches the regular expression given by pattern in the subject string.

If matches is provided, it is filled with the search results. $ Matches [0] will contain the text that matches the entire pattern, $ matches [1] will contain the text that matches the child pattern in the first captured bracket, and so on.

Flags can be the following mark:


PREG_OFFSET_CAPTURE
If this flag is set, the offset of the affiliated string is also returned for each matching result. Note that this changes the value of the returned array, so that each unit is also an array. The first item is the matching string, and the second item is its offset. This tag is available from PHP 4.3.0.

The flags parameter is available since PHP 4.3.0.

Preg_match () returns the number of times pattern matches. Either 0 (no match) or 1 time, because preg_match () will stop searching after the first match. Preg_match_all () indicates that, on the contrary, the end of the subject is always searched. If an error occurs in preg_match (), FALSE is returned.

Tip: If you only want to check whether a string is contained in another string, do not use preg_match (). It can be replaced by strpos () or strstr (), which is much faster.

The above is a description of preg_match () in the manual. I think this function is used for verification, that is, whether a string meets certain requirements. The limitation is that the above statement matches 0 times or 1 time. And the return value is the number of matching times. You can use preg_match_all () when full match is required. it is also worth mentioning that the $ matches array can be used as the return value of the self-mode, sometimes very useful.

Example:


If (preg_match ("/(\ bweb \ B) \ s (\ d)/I", "PHP is the web 45 scripting web 34 language of choice. ", $ match )){
Print "A match was found .";
Print_r ($ match );
} Else {
Print "A match was not found .";
}

?>

// Obtain the host name from the URL
Preg_match ("/^ (http :\/\/)? ([^ \/] +)/I ",
Http://www.php.net/index.html, $ matches );
$ Host = $ matches [2];

// Obtain the following two segments from the host name
Preg_match ("/[^ \. \/] + \. [^ \. \/] + $/", $ host, $ matches );
Echo "domain name is: {$ matches [0]} \ n ";
?>

Preg_match_all
(PHP 3> = 3.0.9, PHP 4, PHP 5)

Preg_match_all -- perform global regular expression matching

This function is clearly explained in the manual, so we will not explain it much.
Description
Int preg_match_all (string pattern, string subject, array matches [, int flags])


Search all the content that matches the regular expression given by pattern in the subject and put the result in the matches in the order specified by flags.

After the first match is found, the next search starts from the end of the previous match.

Flags can be a combination of the following tags (note that it is meaningless to combine PREG_PATTERN_ORDER and PREG_SET_ORDER ):


PREG_PATTERN_ORDER
Sort the results to make $ matches [0] an array that matches all modes, $ matches [1] An array consisting of strings that match the child pattern in the first parentheses, and so on.



Preg_match_all ("| <[^>] +> (.*) ] +> | U ",
" Example:

This is a test

",
$ Out, PREG_PATTERN_ORDER );
Print $ out [0] [0]. ",". $ out [0] [1]. "\ n ";
Print $ out [1] [0]. ",". $ out [1] [1]. "\ n ";
?>

This example will output:

Example:,

This is a test


Example:, this is a test


Therefore, $ out [0] contains a string that matches the entire pattern, and $ out [1] contains a string between a pair of HTML tags.



PREG_SET_ORDER
Sort the results so that $ matches [0] is the array of the first set of matching items, $ matches [1] is the array of the second set of matching items, and so on.


Preg_match_all ("| <[^>] +> (.*) ] +> | U ",
" Example:

This is a test

",
$ Out, PREG_SET_ORDER );
Print $ out [0] [0]. ",". $ out [0] [1]. "\ n ";
Print $ out [1] [0]. ",". $ out [1] [1]. "\ n ";
?>

This example will output:

Example:, Example:

This is a test

, This is a test




In this example, $ matches [0] is the first matching result, and $ matches [0] [0] contains the text matching the entire pattern, $ matches [0] [1] contains text matching the first sub-mode, and so on. Similarly, $ matches [1] is the second group of matching results, and so on.

PREG_OFFSET_CAPTURE
If this flag is set, the offset of the affiliated string is also returned for each matching result. Note that this changes the value of the returned array, so that each unit is also an array. The first item is the matching string, and the second item is its offset in the subject. This tag is available from PHP 4.3.0.


If no flag is provided, it is assumed to be PREG_PATTERN_ORDER.

Returns the number of matching times (which may be zero) for the entire mode. If an error occurs, FALSE is returned.

Example 1. retrieve all phone numbers from a text

Preg_match_all ("/\(? (\ D {3 })? \)? (? (1) [\-\ s]) \ d {3}-\ d {4}/x ",
"Call 555-1212 or 1-800-555-1212", $ phones );
?>



Example 2. search for matched HTML tags (greedy)

// \ 2 is an example of reverse reference. its meaning in PCRE is
// Match the content in the second set of parentheses in the regular expression itself. In this example
// It Is ([\ w] + ). Because the string is enclosed in double quotation marks
// Add a backslash.
$ Html =" Bold textClick me ";

Preg_match_all ("/(<([\ w] +) [^>] *> )(. *) (<\/\ 2>)/", $ html, $ matches );

For ($ I = 0; $ I <count ($ matches [0]); $ I ++ ){
Echo "matched:". $ matches [0] [$ I]. "\ n ";
Echo "part 1:". $ matches [1] [$ I]. "\ n ";
Echo "part 2:". $ matches [3] [$ I]. "\ n ";
Echo "part 3:". $ matches [4] [$ I]. "\ n ";
}
?>



Preg_quote
(PHP 3> = 3.0.9, PHP 4, PHP 5)

Preg_quote -- escape regular expression characters
Description
String preg_quote (string str [, string delimiter])


Preg_quote () takes str as the parameter and adds a backslash before each character that belongs to the regular expression syntax. If you need to use a dynamically generated string as the pattern for matching, you can use this function to escape the special characters that may be contained in it.

If the optional parameter delimiter is provided, the character is also escaped. It can be used to escape the delimiters required by the PCRE function. The most common delimiters are diagonal lines /.

Special characters in a regular expression include:. \ + *? [^] $ () {}=! <> | :.

Note: This function can be safely used for binary objects.

The above is the explanation in the manual, and it is quite clear that I will not talk about it much. In addition, there is a note in the manual that this function can be safely used for binary objects, which is very useful.

Example 1. preg_quote () example

$ Keywords = '$40 for a g3/100 ';
$ Keywords = preg_quote ($ keywords ,'/');
Echo $ keywords; // returns \40 40 for a g3 \/400
?>



Example 2. add italic characters to a word in a text

// In this example, preg_quote ($ word) is used to make the asterisk out of the regular expression.
// Has a special meaning.

$ Textbody = "This book is * very * difficult to find .";
$ Word = "* very *";
$ Textbody = preg_replace ("/". preg_quote ($ word )."/",
" ". $ Word ."",
$ Textbody );
?>



The next step is to use the ultra-flexible, super-powerful, and widely used preg_replace functions.

Preg_replace
(PHP 3> = 3.0.9, PHP 4, PHP 5)

Preg_replace -- Search and replace regular expressions
Description
Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])


Search for matches in pattern in subject and replace them with replacement. If limit is specified, only limit matches are replaced. if limit is omitted or its value is-1, all matches are replaced.

Replacement can contain \ n form or (from PHP 4.0.4) $ n form of reverse reference. The latter is preferred. Each such reference will be replaced with the text that matches the child pattern in the nth captured parentheses. N can be from 0 to 99, where \ 0 or $0 indicates the text matched by the entire mode. Count left parentheses from left to right (starting from 1) to obtain the number of child modes.

When the replacement mode is followed by a number after a reverse reference (that is, the number next to a matching mode), the familiar \ 1 symbol cannot be used to represent a reverse reference. For example, \ 11 will make preg_replace () confused that the reverse reference of \ 1 is followed by a number 1 or a reverse reference of \ 11. In this example, \ $ {1} 1 is used. This will form an isolated $1 reverse reference, and make the other 1 just plain text.

If a match is found, the replaced subject is returned. Otherwise, the original unchanged subject is returned.

Each parameter (except limit) of preg_replace () can be an array. If both pattern and replacement are arrays, they are processed in the order in which their key names appear in the array. This is not necessarily the same as the numerical order of the index. If indexes are used to identify which pattern will be replaced by which replacement, ksort () should be used to sort the array before preg_replace () is called.

If the subject is an array, it searches and replaces each item in the subject and returns an array.

If both pattern and replacement are arrays, preg_replace () extracts values from them to search and replace subject. If the value in replacement is less than that in pattern, an empty string is used as the remaining replacement value. If pattern is an array and replacement is a string, this string is used as the replacement value for each value in pattern. In turn, it makes no sense.

The/e modifier enables preg_replace () to treat the replacement parameter as PHP code (after appropriate reverse references are replaced ). Tip: Make sure that the replacement constitutes a valid PHP code string. otherwise, PHP will report a syntax parsing error in the row containing preg_replace.

Note: The limit parameter is added after PHP 4.0.1pl2.

I think its strength is that it can not only process strings, but also arrays, and its reverse reference function is very flexible. Basically, it can meet most of the requirements of ordinary users. if he is not competent, we also have the preg_replace_callback () function, which can be customized to meet your advanced requirements. Such as designing filters.

Preg_replace_callback
(PHP 4> = 4.0.5, PHP 5)

Preg_replace_callback -- use the callback function to search and replace regular expressions.
Description
Mixed preg_replace_callback (mixed pattern, callback, mixed subject [, int limit])


The behavior of this function is almost the same as that of preg_replace (), except that a replacement parameter is provided, but a callback function is specified. This function uses the matching array in the target string as the input parameter and returns the string to be replaced.

Example 1. preg_replace_callback () example

// This article was used in 2002,
// Now you want to use it for January 1, 2003
$ Text = "maid day is 04/01/2002 \ n ";
$ Text. = "Last christmas was 12/24/2001 \ n ";

// Callback function
Function next_year ($ matches ){
// Generally: $ matches [0] is a complete match.
// $ Matches [1] is the matching item of the child pattern in the first bracket.
// And so on
Return $ matches [1]. ($ matches [2] + 1 );
}

Echo preg_replace_callback (
"| (\ D {2}/\ d {2}/) (\ d {4}) | ",
"Next_year ",
$ Text );

// The result is:
// Else L fools day is 04/01/2003
// Last christmas was 12/24/2002
?>


You'll often need the callback function for a preg_replace_callback () in just one place. in this case you can use create_function () to declare an anonymous function as callback within the call to preg_replace_callback (). by doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback functions name not used anywhere else.

For friends who use the preg_replace_callback () function, you should call back the callback function (otherwise, it is not better to use preg_replace directly), but it is often used only one place. In this case, you can use create_function () to declare an anonymous function as the callback function of preg_replace_callback. In this way, we have met the need to declare information, and there is no confusion due to this function name that will no longer be used.

Example 2. preg_replace_callback () and create_function ()

/* A UNIX-style command line filter that includes
* Convert uppercase letters to lowercase letters */

$ Fp = fopen ("php: // stdin", "r") or die ("can't read stdin ");
While (! Feof ($ fp )){
$ Line = fgets ($ fp );
$ Line = preg_replace_callback (
'|

\ S * \ w | ',
Create_function (
// It is critical to use single quotes,
// Otherwise, replace all $ with \ $.
'$ Matches ',
'Return strtolower ($ matches [0]);'
),
$ Line
);
Echo $ line;
}
Fclose ($ fp );
?>


Finally

Preg_split
(PHP 3> = 3.0.9, PHP 4, PHP 5)

Preg_split -- use a regular expression to split a string
I will not go into details.
Description
Array preg_split (string pattern, string subject [, int limit [, int flags])


Returns an array that contains the substrings separated by subject along the boundary matching pattern.

If the limit parameter is specified, a maximum of limit substrings are returned. if the limit parameter is-1, there is no limit. it can be used to specify the optional parameter flags.

Flags can be any combination of the following tags (using bitwise OR operator | combination ):


PREG_SPLIT_NO_EMPTY
If this flag is set, preg_split () returns only non-null components.

PREG_SPLIT_DELIM_CAPTURE
If this mark is set, the parentheses expression in the delimiter mode will also be captured and returned. This tag is added to PHP 4.0.5.

PREG_SPLIT_OFFSET_CAPTURE
If this tag is set, the offset of the affiliated string is also returned for each matching result. Note that this changes the value of the returned array, so that each unit is also an array. The first item is the matching string, and the second item is its offset in the subject. This tag is available from PHP 4.3.0.


Tip: If you do not need the regular expression function, you can choose to use a faster (or simpler) alternative function, such as explode () or str_split ().

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.