Analysis of common regular function examples in PHP

Source: Internet
Author: User
Tags function examples
This article mainly introduces the common regular function of PHP, summarizes and analyzes the common functions of PHP regular expressions, including the functions of Preg_replace, Preg_match and Preg_match_all functions, the usage methods and the related precautions. A friend you need can refer to the following

This paper summarizes common regular functions of PHP. Share to everyone for your reference, as follows:

1. Mixed preg_replace (mixed pattern, mixed replacement, mixed subject, [, int limit])

function function: used for searching and replacing regular expressions.

pattern: Regular expression.
replacement: replace the content.
subject: The object that needs to match the substitution.
limit: Optional, specifies the number of replacements, and if the limit is omitted or the value is-1, all occurrences will be replaced.

Additional Information

①replacement can contain reverse references in the form of \\n or $n, preferring to use the latter. Each of these references will be replaced with text that matches the sub-pattern in the nth captured parentheses. n can be from 0 to 99, where \\0 or $ refers to text that is matched by the entire pattern. The left parenthesis is counted from left to right (starting at 1) to get the number of sub-patterns.

② A reverse reference is immediately followed by a number (such as \\11) for the replacement pattern, and the \ \ symbol cannot be used to represent the inverse reference. Because it would make preg_replace () unclear whether you want a \\1 inverse reference followed by a number 1 or a \\11 inverse reference. The workaround is to use \${1}1. This creates an isolated reverse reference, and makes the other 1 simple text.

③ The above parameter can be an array except for limit. If both pattern and replacement are arrays, they will be processed in the order in which their key names appear in the array, which is not necessarily the same as the numeric order of the indexes. If you use an index to identify which pattern will be replaced by which replacement, you should sort the array with the Ksort () function before calling Preg_replace ().

Example 1:

<?php$str = "The quick brown fox jumped over the lazy dog."; $str = preg_replace ('/\s/', '-', $str); Echo $str; >

The output is:

The-quick-brown-fox-jumped-over-the-lazy-dog.

Example 2, using an array:

<?php$str = "The quick brown fox jumped over the lazy dog."; $patterns [0] = "/quick/"; $patterns [1] = "/brown/"; $patterns [2] = "/fox/"; $replacements [2] = "Bear"; $replacements [1] = " Black "; $replacements [0] =" slow ";p rint preg_replace ($patterns, $replacements, $STR);/* Output: The bear black slow jumped over The Lazy Dog.*/ksort ($replacements);p rint preg_replace ($patterns, $replacements, $STR);/* Output: The slow black bear jumped Over the lazy dog.*/?>

Example 3, using a reverse reference:

<?php$str = ' <a href= ' http://www.baidu.com/' >baidu</a> other characters <a href= ' http://www.sohu.com/' >sohu </a> '; $pattern = "/<a\s ([\s\s]*?) > ([\s\s]*?) <\/a>/i ";p rint preg_replace ($pattern, ' \\2 ', $str);? >

The output is:

Baidu Other characters Sohu

This example shows all of the <a></a> tags in the text removed.

2. int Preg_match (string $pattern, String $subject [, Array & $matches [, int $flags =0 [, int $offset = 0]])

function function: Searches for a match between the subject and the regular expression given by the pattern.

Pattern: The type of string to search for.
subject: input string.
matches: If a parameter matches is supplied, it will be populated as a search result, $matches [0] will contain the full pattern match to the text, $matches [1] will contain the text to which the first capturing subgroup matches.
flags: Can be set to Preg_offset_capture, if this token is passed, the string offset (relative to the target string) will be appended to each occurrence of the match returned.
Note: This changes the padding to the matches array so that each element becomes a string that is matched to by the No. 0 element, and the 1th element is the offset of the matching string in the target string subject.
offset: Typically, the search starts with the target string, and an optional parameter, offset, is used to specify an unknown start search (in bytes) from the target string.

3. int Preg_match_all (string $pattern, String $subject [, Array & $matches [, int $flags =preg_pattern_order [, int $off Set=0]])

function function: Searches all matches in subject that match the pattern given regular expression and outputs them in flag-specified order to matches.

After the first match is found, the subsequence continues to search from the last matching location.

Pattern: The mode to search, in string form.
subject: input string.
matches: multidimensional array, as output parameter output after all matching results, array sorting is specified by flags.
flags: Can be used in conjunction with the following tags (note that preg_pattern_order and Preg_set_order cannot be used at the same time):

Preg_pattern_order

Results sorted to $matches[0] saves all matches for the full pattern, $matches [1] saves all matches for the first subgroup, and so on.

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

The above routines will output:

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

Therefore, $out [0] is an array containing a string that matches the full pattern, $out [1] is an array containing the string within the closed tag.

Preg_set_order

The result sort is $matches[0] contains all matches that were obtained for the first match (including subgroups), $matches [1] is an array that contains all matches (including subgroups) to the second match, and so on.

<?phppreg_match_all ("|<[^>]+> (. *) </[^>]+>| U ",  " <b>example: </b><p align=\ "Left\" >this is a test</p> ",  $out, Preg_set_order); echo $out [0][0]. ", " . $out [0][1]. "\ n"; echo $out [1][0]. ", " . $out [1][1]. "\ n";? >

The above routines will output:

<b>example: </b>, example:
<p align= "left" >this is a test</p>

Preg_offset_capture

If this token is passed, each found match is returned with an offset to its relative target string. Note that this alters each of the matching result string elements in the matches, making it a No. 0 element to match the result string, and the 1th element as the offset of the matching result string in subject.

If no sort mark is given, it is assumed to be set to Preg_pattern_order.

Offset: Typically, the lookup starts at the beginning of the target string, and optional parameter offset is used to start the search (in bytes) from the specified position in the target string.

The above is the whole content of this article, I hope that everyone's study has helped.


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.