Examples of common php regular functions and php instances

Source: Internet
Author: User

Examples of common php regular functions and php instances

This example summarizes common php regular functions. We will share this with you for your reference. The details are as follows:

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

Function: Used to search and replace regular expressions.

Pattern: regular expression.
Replacement: the content to be replaced.
Subject: the object to be replaced.
Limit: (optional) Number of replicas. If limit is omitted or its value is-1, all the matches will be replaced.

Additional instructions

① Replacement can contain \ n or $ n reverse references. 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 reverse reference followed by a number (for example, \ 11), the \ symbol cannot be used to represent the reverse reference. This will cause the preg_replace () to be confused about whether a reverse reference of \ 1 is followed by a number 1 or a reverse reference of \ 11. The solution is to use \ $ {1} 1. This will form an isolated $1 reverse reference, and make the other 1 just plain text.

③ The above parameters can be an array except limit. If pattern and replacement are both 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 you use indexes to identify which pattern will be replaced by which replacement, you should use the ksort () function to sort the array before calling preg_replace.

Example 1:

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

Output result:

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

Example 2: use 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"; print preg_replace ($ patterns, $ replacements, $ str);/* output: The bear black slow jumped over the lazy dog. */ksort ($ replacements); print preg_replace ($ patterns, $ replacements, $ str);/* output: The slow bl Ack bear jumped over the lazy dog. */?>

Example 3: Use 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 "; print preg_replace ($ pattern, '\ 2', $ str);?>

Output result:

Other baidu characters sohu

This example shows how to remove all the <a> </a> labels in the text.

2. int preg_match (string $ pattern, string $ subject [, array & $ matches [, int $ flags = 0 [, int $ offset = 0])

Function: search for a match between the regular expression specified by subject and pattern.

Pattern: The pattern to be searched, string type.
Subject: input string.
Matches: If the matches parameter is provided, it will be filled with search results, $ matches [0] will contain the full mode matching to the text, $ matches [1] will contain the text matched by the first capture sub-group.
Flags: it can be set to PREG_OFFSET_CAPTURE. If this flag is passed, a string offset (relative to the target string) will be appended to the response for each occurrence of the match ).
Note: This will change the padding to the matches array so that each element becomes a matched string from 0th elements, and 1st elements are the offset of the matched string in the target string subject.
Offset: Generally, the search starts from the target string. The optional parameter offset is used to specify an unknown start from the target string (in bytes ).

3. int preg_match_all (string $ pattern, string $ subject [, array & $ matches [, int $ flags = PREG_PATTERN_ORDER [, int $ offset = 0])

Function: search all matching results of the regular expression specified by pattern in subject and output them to matches in the order specified by flag.

After the first match is found, the Child sequence continues searching from the last match position.

Pattern: The pattern to be searched, In the string format.
Subject: input string.
Matches: multi-dimensional array. All matching results are output as output parameters. The array is sorted by flags.
Flags: can be used with the following labels (note that PREG_PATTERN_ORDER and PREG_SET_ORDER cannot be used simultaneously ):

PREG_PATTERN_ORDER

The results are sorted as $ matches [0] To save all matches in the complete mode, $ matches [1] to save all matches in the first subgroup, and so on.

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

The above routine will output:

<B> example: </B>, <div align = left> this is a test </div>
Example:, this is a test

Therefore, $ out [0] is an array containing strings matching the full mode, and $ out [1] is an array containing strings in the closed tag.

PREG_SET_ORDER

The result is sorted as $ matches [0] and contains all matching results (including sub-groups) after the first match. $ matches [1] contains all matching results (including sub-groups) after the second match) array, and so on.

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

The above routine will output:

<B> example: </B>, example:
<Div align = "left"> this is a test </div>, this is a test

PREG_OFFSET_CAPTURE

If this tag is passed, the offset relative to the target string will be increased when each detected match is returned. note that this will change each matching result string element in matches and make it a 0th element as the matching result string, and the 1st element as the offset of the matching result string in the subject.

If no sorting tag is specified, it is set to PREG_PATTERN_ORDER.

Offset: Generally, the search starts from the start position of the target string. The optional parameter offset is used to start searching from the specified position in the target string (in bytes ).

PS: here we will provide two very convenient Regular Expression tools for your reference:

JavaScript Regular Expression online testing tool:
Http://tools.jb51.net/regex/javascript

Regular Expression generation tool:
Http://tools.jb51.net/regex/create_reg

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.