A summary of the regular processing functions of PHP _php Foundation

Source: Internet
Author: User
Tags anonymous html tags mixed stdin

Preg_grep
(PHP 4, PHP 5)

Preg_grep--Returns the array cells that match the pattern
Description
Array Preg_grep (string pattern, array input [, int flags])


Preg_grep () returns an array that includes the cells in the input array that match the given pattern patterns.

Flags can be the following tags:


Preg_grep_invert
If passed into this tag, preg_grep () returns the cells in the input array that do not match the given pattern. This tag is available from PHP 4.2.0.


From PHP 4.0.4, the result returned by Preg_grep () is indexed using the key name from the input array. If you do not want such a result, use Array_values () to index the result returned by Preg_grep ().

Above is a description of Preg_grep () on the manual. First of all, this is a Perl-compatible regular function, so I guess Preg_grep means P (Perl) reg (Regular) _grep, which is characterized by its use as an array, which can be used as a regular match in a multidimensional array. A matching or mismatched array can be returned through the flags parameter. It is more efficient than using foreach (...) {if ...} Structure is much faster (not validated) and can match complex patterns. In search, separation and other applications in the application is not small.

Cases:

?
$arr = Array (' abc ' =>12.213, ' BB ' =>12345, ' ba ' =>23.2321,34.3, ' => ' 3.3 ', ' 23434 ' => ' BBB ');

Returns all the array elements that contain 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--a regular expression match
Description
int Preg_match (string pattern, string subject [, array matches [, int flags]])


Searches the subject string for what matches the regular expression given by pattern.

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

Flags can be the following tags:


Preg_offset_capture
If you set this tag, the matching result for each occurrence also returns its subordinate string offset. Note that this changes the value of the returned array so that each cell is also an array, where the first item is a matching string and the second is its offset. This tag is available from PHP 4.3.0.

The flags parameter is available from PHP 4.3.0.

Preg_match () returns the number of times the pattern was matched. Either 0 times (no match) or 1 times, because Preg_match () stops the search after the first match. Preg_match_all () on the contrary, will search until the end of the subject. If error Preg_match () returns FALSE.

Tip: Do not use Preg_match () if you only want to see if a string is contained in another string. You can use Strpos () or strstr () instead, much faster.

The above is a description of Preg_match () in the manual, and I think the function is that he can do the validation, that is, whether a string meets a specific requirement. The limitation is that the above is either matched 0 times or 1 times. And the return value is the number of matches. Use Preg_match_all () when a full match is required. Also worth mentioning is the role of the $matches array, can do the return value of the mode, sometimes useful.

Cases:

?

if (Preg_match ("/(\bweb\b) \s (\d)/I", "PHP is the Web Scripting Web language of choice.", $match))
Print "A match was found.";
Print_r ($match);
} else {
Print "A match is not found.";
}

?>

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

To get 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--Global regular expression matching

The explanation of the function is very clear in the manual, so it's not much to explain.
Description
int Preg_match_all (string pattern, string subject, array matches [, int flags])


Searches in subject for all occurrences of the regular expression matched with pattern and places the results in the matches in the order specified by the flags.

After the first match is searched, the next search starts at the end of the previous match.

Flags can be a combination of the following tags (note that preg_pattern_order and Preg_set_order are combined to make no sense):


Preg_pattern_order
Sorts the results to make an array that $matches [0] match for all patterns, $matches [1] An array of strings that match the child patterns in the first bracket, and so on.



<?php
Preg_match_all ("|<[^>]+> (. *) </[^>]+>| U ",
"<b>example: </b><div align=left>this is a test</div>",
$out, Preg_pattern_order);
Print $out [0][0]. ",". $out [0][1]. " \ n ";
Print $out [1][0]. ",". $out [1][1]. " \ n ";
?>

This example will output:

<b>example: </b&gt, <div Align=left>this is a test</div>
Example:, this is a test


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



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


<?php
Preg_match_all ("|<[^>]+> (. *) </[^>]+>| U ",
"<b>example: </b><div align=left>this is a test</div>",
$out, Preg_set_order);
Print $out [0][0]. ",". $out [0][1]. " \ n ";
Print $out [1][0]. ",". $out [1][1]. " \ n ";
?>

This example will output:

<b>example: </b>, example:
<div Align=left>this is a test</div>




In this example, $matches [0] is the first set of matching results, $matches [0][0] contains text that matches the entire pattern, $matches [0][1] contains text that matches the first child mode, and so on. Similarly, $matches [1] is the second set of matching results, and so on.

Preg_offset_capture
If you set this tag, the matching result for each occurrence also returns its subordinate string offset. Note that this changes the value of the returned array so that each cell is also an array, where the first item is a matching string and the second item is its offset in the subject. This tag is available from PHP 4.3.0.


If no token is given, it is assumed to be preg_pattern_order.

Returns the number of times the entire pattern match (possibly 0), or FALSE if an error is returned.

Example 1. Get all the phone numbers from a text

<?php
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 matching HTML tags (greedy)

<?php
\\2 is an example of a reverse reference, whose meaning in PCRE is
You must match the contents of the second set of parentheses within the regular expression itself, in this case
Is ([\w]+). Because the string is in double quotes, you need
Add a backslash.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

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 a parameter and adds a backslash to each character that belongs to the regular expression syntax. If you need to match a dynamically generated string as a pattern, you can use this function to escape the special characters that may be contained in it.

If an optional parameter delimiter is provided, the character is also escaped. Can be used to escape the delimiters required by the PCRE function, the most commonly used delimiter is a slash/.

Special characters for regular expressions include:. \ + * ? [ ^ ] $ ( ) { } = ! < > | :。

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

It's a manual explanation, and it's quite clear, not to mention it, but there's also a note in the manual that says that the function is safe for binary objects, which is useful.

Example: 1. Preg_quote () example

<?php
$keywords = ' $ for a g3/400 ';
$keywords = Preg_quote ($keywords, '/');
Echo $keywords; Returns \$40 for a g3\/400
?>



Example 2. Add a italic mark to a word in a text

<?php
In this case, Preg_quote ($word) is used to keep the asterisk out of the regular expression
Have a special meaning.

$textbody = "This book are *very* difficult to find.";
$word = "*very*";
$textbody = Preg_replace ("/". Preg_quote ($word). /",
"<i>". $word. " </i> ",
$textbody);
?>



The next step is to apply the Preg_replace function, which is super flexible and powerful, and uses a very wide range of functions.

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

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


Searches the subject for a match in pattern mode and replaces it with replacement. If limit is specified, only the limit match is substituted, and if limit is omitted or the value is-1, all occurrences are replaced.

Replacement can contain \\n forms or reverse references (from PHP 4.0.4) $n form, preferred to use the latter. Each such reference is replaced with the text that matches the child pattern in the nth captured bracket. n can be from 0 to 99, where \\0 or $ refers to text that is matched by the entire pattern. Count the left parenthesis from left to right (starting from 1) to get the number of child modes.

A backward reference cannot be represented by a familiar \\1 symbol when the replacement pattern is followed by a number (that is, a number immediately following a matching pattern) after a reverse reference. \\11, for example, will make preg_replace () want a \\1 reverse reference followed by a number 1 or a \\11 reverse reference. In this case, the workaround is to use \${1}1. This creates an isolated, reverse reference, and the other 1 is just plain text.

If a match is searched, the replaced subject is returned, otherwise the original subject is returned.

Each parameter (except the limit) of the 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 numeric order of the index. If you use an index to identify which pattern will be replaced by which replacement, you should sort the array by Ksort () before calling Preg_replace ().

If the subject is a group, the search and replace is performed on each item in subject and an array is returned.

If both pattern and replacement are arrays, the preg_replace () then takes the value separately from the values to search for and replace the subject. If the value in replacement is less than in pattern, the 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. There is no point in the converse.

The/e modifier causes preg_replace () to use the replacement parameter as PHP code (after replacing the appropriate reverse reference). Tip: To make sure that replacement makes up a valid PHP code string, PHP will have a syntax resolution error in the report containing Preg_replace ().

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

I think the strong thing is that he not only can handle the string, but also can handle the array, and his reverse reference function is very flexible. Basically he can meet most of the needs of ordinary users, if he is not competent, then we have the Preg_replace_callback () function, you can customize the callback function to meet your advanced requirements. such as the design of filters.

Preg_replace_callback
(PHP 4 >= 4.0.5, PHP 5)

Preg_replace_callback--using callback functions to perform search and replace of regular expressions
Description
Mixed Preg_replace_callback (mixed pattern, callback callback, mixed subject [, int limit])


The behavior of this function is almost the same as Preg_replace (), except that instead of providing a replacement parameter, you specify a callback function. The function takes an array of matches in the target string as an input parameter and returns a string for substitution.

Example 1. Preg_replace_callback () example

<?php
This text is used for 2002 of years,
Now want to make it available for 2003
$text = "April fools day is 04/01/2002\n";
$text. = "Last Christmas was 12/24/2001\n";

callback function
function Next_year ($matches) {
Typically: $matches [0] is a complete match
$matches [1] is a match for a child pattern in the first bracket
Analogy
return $matches [1]. ($matches [2]+1);
}

Echo Preg_replace_callback (
"| (\d{2}/\d{2}/) (\d{4}) | ",
"Next_year",
$text);

The results are:
April 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 your can use Create_function () to declare a anonymous function as callback within the call to Preg_replace_ca Llback (). By doing it this way you have all information for "call in one" and do not clutter the function namespace with a C Allback functions name not used anywhere else.

For a friend who uses the Preg_replace_callback () function, you should need to return the callback function (otherwise it is not better to use the preg_replace), but it is often only used in one place. So you can use Create_function () to declare an anonymous function as the callback function of Preg_replace_callback (). In this way, we meet the need to declare information and not be confused by the name of a function that is not used again.

Example 2. Preg_replace_callback () and Create_function ()

<?php
/* A UNIX-style command-line filter that starts each paragraph
* Convert capital 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 (
' |<p>\s*\w| ',
Create_function (
It's critical to use single quotes here,
Otherwise, replace all of the $ \$
' $matches ',
' Return strtolower ($matches [0]); '
),
$line
);
Echo $line;
}
Fclose ($FP);
?>


Finally,

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

Preg_split--Splitting a string with a regular expression
Don't repeat it.
Description
Array Preg_split (string pattern, string subject [, int limit [, int flags]])


Returns an array containing substrings that are split along the bounds that match the pattern in subject.

If limit is specified, the maximum number of limit substrings is returned, and if limit is-1, it means there are no restrictions that can be used to continue specifying the optional parameter flags.

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


Preg_split_no_empty
If this tag is set, the Preg_split () returns only the Non-empty component.

Preg_split_delim_capture
If this tag is set, the bracket expression in the delimiter pattern is also captured and returned. This tag is added to the PHP 4.0.5.

Preg_split_offset_capture
If you set this tag, if you set this tag, the matching result for each occurrence also returns its subordinate string offset. Note that this changes the value of the returned array so that each cell is also an array, where the first item is a 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 functionality of a regular expression, you can choose to use a faster (and simpler) substitution 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.