php function preg_replace () regular replace all strings that match the criteria

Source: Internet
Author: User
Tags alphabetic character php regular expression preg

PHP preg_replace () Regular substitution, unlike JavaScript regular substitution, PHP preg_replace () defaults to the element that replaces all symbol matching Criteria .

Preg_replace (regular expression, replace with, string, maximum number of replacements "default-1, countless times", number of replacements)

The regular expressions for most languages are similar, but there are subtle differences.

PHP Regular Expressions

Regular characters the regular explanation
\ Marks the next character as a special character, or a literal character, or a backward reference, or an octal escape. For example, "\ n" matches the character "n". "\\n" matches a line break. The sequence "\ \" matches "\" and "\ (" Matches "(".
^ Matches the starting position of the input string. If the multiline property of the RegExp object is set, ^ also matches the position after "\ n" or "\ r".
$ Matches the end position of the input string. If the multiline property of the RegExp object is set, $ also matches the position before "\ n" or "\ r".
* Matches the preceding subexpression 0 or more times. For example, zo* can match "z" and "Zoo". * Equivalent to {0,}.
+ Matches the preceding subexpression one or more times. For example, "zo+" can Match "Zo" and "Zoo", but not "Z". + equivalent to {1,}.
? Matches the preceding subexpression 0 or one time. For example, "Do (es)?" You can match "do" in "does" or "does".? = {0,1}.
N N is a non-negative integer. Matches the determined n times. For example, "o{2}" cannot match "O" in "Bob", but can match two o in "food".
{N,} N is a non-negative integer. Match at least n times. For example, "o{2,}" cannot match "O" in "Bob", but can match all o in "Foooood". "O{1,}" is equivalent to "o+". "O{0,}" is equivalent to "o*".
{N,m} Both M and n are non-negative integers, where n<=m. Matches at least n times and matches up to M times. For example, "o{1,3}" will match the first three o in "Fooooood". "o{0,1}" is equivalent to "O?". Note that there can be no spaces between a comma and two numbers.
? When the character immediately follows any other restriction (*,+,?,{n},{n,},{n,m}), the matching pattern is non-greedy. The non-greedy pattern matches the searched string as little as possible, while the default greedy pattern matches as many of the searched strings as possible. For example, for the string "Oooo", "O?" A single "O" will be matched, and "o+" will match all "O".
. Point Matches any single character except "\ n". To match any character that includes "\ n", use a pattern like "[\s\s]".
(pattern) Match pattern and get this match. The obtained matches can be obtained from the resulting matches collection, the Submatches collection is used in VBScript, and the $0...$9 property is used in JScript. To match the parentheses character, use "\ (" or "\").
(?:p Attern) Matches pattern but does not get a matching result, which means that this is a non-fetch match and is not stored for later use. This is used in the or character "(|)" It is useful to combine the various parts of a pattern. For example, "Industr (?: y|ies)" is a more abbreviated expression than "industry|industries".
(? =pattern) positive pre-check to match the find string at the beginning of any string matching pattern. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example, "Windows (? =95|98| nt|2000) "Can match" windows "in" Windows2000 ", but does not match" windows "in" Windows3.1 ". Pre-checking does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, rather than starting with the character that contains the pre-check.
(?! Pattern forward negation , matching the lookup string at the beginning of any mismatched pattern string. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example, "Windows (?! 95|98| nt|2000) "Can match" windows "in" Windows3.1 ", but does not match" windows "in" Windows2000 ".
(? <=pattern) Reverse positive pre-check , similar to positive pre-check, just the opposite direction. For example, "(? <=95|98| nt|2000) Windows can match "Windows" in 2000Windows, but not "windows" in "3.1Windows".
(? <!pattern) Reverse negation is similar to positive negative pre-checking, except in the opposite direction. For example "(? <!95|98| nt|2000) Windows can match "Windows" in 3.1Windows, but not "windows" in "2000Windows".
X|y Match x or Y. For example, "Z|food" can match "Z" or "food". "(z|f) Ood" matches "Zood" or "food".
[XYZ] The character set is combined. Matches any one of the characters contained. For example, "[ABC]" can Match "a" in "plain".
[^XYZ] Negative character set. Matches any character that is not contained. For example, "[^ABC]" can match "Plin" in "plain".
[A-z] The character range. Matches any character within the specified range. For example, "[A-z]" can match any lowercase alphabetic character in the range "a" to "Z". Note: The range of characters can be represented only if the hyphen is inside a character group and is between two characters; If the beginning of the character group is out, only the hyphen itself can be represented.
[^a-z] A negative character range. Matches any character that is not in the specified range. For example, "[^a-z]" can match any character that is not in the range "a" to "Z".
\b Matches a word boundary, which is the position between a word and a space. For example, "er\b" can Match "er" in "never", but cannot match "er" in "verb".
\b Matches a non-word boundary. "er\b" can Match "er" in "verb", but cannot match "er" in "Never".
\cx Matches the control character indicated by X. For example, \cm matches a control-m or carriage return. The value of x must be one of a-Z or a-Z. Otherwise, c is considered to be a literal "C" character.
\d Matches a numeric character. equivalent to [0-9].
\d Matches a non-numeric character. equivalent to [^0-9].
\f Matches a page break. Equivalent to \x0c and \CL.
\ n Matches a line break. Equivalent to \x0a and \CJ.
\ r Matches a carriage return character. Equivalent to \x0d and \cm.
\s Matches any whitespace character, including spaces, line breaks, tabs, page breaks, Chinese full-width spaces, and so on. equivalent to [\f\r\n\t\v].
\s Matches any non-whitespace character. equivalent to [^ \f\r\n\t\v].
\ t Matches a tab character. Equivalent to \x09 and \ci.
\v Matches a vertical tab. Equivalent to \x0b and \ck.
\w Matches any word character that includes an underscore. Equivalent to "[a-za-z0-9_]".
\w Matches any non-word character. Equivalent to "[^a-za-z0-9_]".
\xn Match N, where n is the hexadecimal escape value. The hexadecimal escape value must be two digits long for a determination. For example, "\x41" matches "A". "\x041" is equivalent to "\x04&1". ASCII encoding can be used in regular expressions.
\num Matches num, where num is a positive integer. A reference to the obtained match. For example, "(.) \1 "matches two consecutive identical characters.
\ n Identifies an octal escape value or a backward reference. n is a backward reference if \ n is preceded by at least one of the sub-expressions obtained. Otherwise, if n is the octal number (0-7), N is an octal escape value.
\nm Identifies an octal escape value or a backward reference. If at least NM has obtained a subexpression before \nm, then NM is a backward reference. If there are at least N fetches before \nm, then n is a backward reference followed by the literal m. If none of the preceding conditions are met, if both N and M are octal digits (0-7), then \nm will match the octal escape value nm.
\nml If n is an octal number (0-7) and both M and L are octal digits (0-7), the octal escape value NML is matched.
\un Match N, where N is a Unicode character represented by four hexadecimal digits. For example, \u00a9 matches the copyright symbol (©).

The above table is a comprehensive interpretation of regular expressions, while the regular characters in a trademark have special meanings, and no longer represent the meaning of the original character. As in regular expressions, "+" does not represent a plus, but instead represents a match one or more times. If you want "+" to indicate a plus, you need to precede it with "\" to escape, that is, "\+" for the plus sign.

The 1+1=2 regular expression is: 1\+1=2
And the regular expression 1+1=2 can represent, multiple 1=2, namely:
11=2 Regular expression: 1+1=2
111=2 Regular expression: 1+1=2
1111=2 Regular expression: 1+1=2
......

This means that all regular characters have a specific meaning, and if they need to be used again to denote the meaning of the original character, they need to be escaped with "\" in front, even if the non-regular character is escaped with "\".

The 1+1=2 regular expression can also be: \1\+\1\=\2
All characters are escaped, but this is not recommended.

The regular expression must be surrounded by delimiters, in JavaScript the delimiter is "/", whereas in PHP, it is more common to use the "/" bound, you can use the "#" bound, but also outside the need to enclose in quotation marks.

If the regular expression contains these delimiters, you need to escape these characters.

PHP Regular Expression delimiter

Most language regular expressions are "/" as delimiters, and in PHP, you can also use the "#" bound, if the string contains a large number of "/" characters, in the use of "/" bound, you need to escape these "/", and use "#" do not need to escape, more concise.

<?php$subject= ' Chan Yunlai PHP blog URL is http://blog.snsgou.com/_blog/, can you replace this URL with the correct URL? '///The above requirement is to replace the Http://blog.snsgou.com/_blog with http://blog.snsgou.com///. :-All regular symbols, so you need to escape, and/is the delimiter, if the string contains/delimiters, you need to escape echo preg_replace ('/http\:\/\/www\.qianyunlai\.com\/\_blog\//', ' http:/ /blog.snsgou.com/', $subject); Echo ' <br/> ';//In #作为定界符,/is no longer the meaning of the delimiter, there is no need to escape. echo preg_replace (' #http \://www\.qianyunlai\.com/\_blog/# ', ' http://blog.snsgou.com/', $subject);//The above two outputs are the same, " Chan Yunlai PHP Blog URL is http://blog.snsgou.com/, can you replace this URL with the correct URL? "?>

Using the two PHP regular replacement code above, we can see that if a regular statement contains a lot of "/", it is OK to use "/" or "#" to do the delimiter, but use "#" to make the code look more concise. However, it is recommended that you keep the "/" as the delimiter, because in languages such as JavaScript, you can only use "/" as a delimiter, so that it forms a habit and runs through other languages.

PHP Regular Expression modifiers

Modifier is placed after the PHP regular expression delimiter "/" before the regular expression trailing quotation marks.

I ignore case, match does not consider case

m Multi-line independent matching, if the string does not contain [\ n] and other line characters like normal regular.

s sets the regular symbol. You can match the newline character [\ n], if not set, the regular symbol. The newline character cannot be matched \ n.

x ignores spaces that are not escaped

e eval () executes the function on the matched element.

A front anchor, constraint matching only starts the search from the target string

d Locks $ as the end, and if there is no D, if the string contains a newline character such as [\ n], the $ still matches the line break. If the modifier m is set, the modifier D is ignored.

S Analysis of non-anchoring matching

U is not greedy, if you add "?" after the regular character quantifier, you can restore greed

X Open an incompatible attachment with Perl

u forces the string to be UTF-8 encoded, which is generally required in non-UTF-8 encoded documents. It is recommended that you do not use this in UTF-8 environments.

If you are familiar with JavaScript regular expressions, you may be familiar with the modifier "G" of a JavaScript regular expression, which represents matching all eligible elements. In PHP regular substitution, it is the element that matches all symbol conditions, so there is no JavaScript modifier "G".

PHP is Chinese and ignores case

PHP preg_replace () is case-sensitive and can only match strings within ASCII encodings, and if you need to match characters that are not case sensitive and Chinese, you need to add the appropriate modifier I or U.

<?php$subject= ' Chan Yunlai PHP blog URL: http://www. qianyunlai.com/';//Case different, output "Chan Yunlai PHP Blog URL: http://www. qianyunlai.com/"Echo preg_replace ('/qian/', ' QIAN ', $subject); Echo ' <br/> ';//Ignore case, execute replace output" Chan Yunlai PHP Blog URL:/http blog.snsgou.com/"Echo preg_replace ('/qian/i ', ' QIAN ', $subject); Echo ' <br/> ';//Force UTF-8 Chinese, perform replace, output" Chan Yunlai PHP Blog: http://www. qianyunlai.com/"Echo preg_replace ('/website/u '," ', $subject);? >

Both case and Chinese are sensitive in PHP, but in JavaScript regular, it is only case sensitive, ignoring case is also through modifier I, but JavaScript does not need to tell whether it is a special character such as UTF-8 Chinese, it can match Chinese directly.

PHP Regular line Break instance

When a newline character is encountered by a PHP regular expression, the line break is treated as a normal characters in the middle of the string. While the generic symbol cannot match \ n, a string with a newline character will have many important points to be encountered.

<?php$subject= "snsgou.com\nis\nloving\nyou";//want to replace the above $subject with Snsgou.comecho preg_replace ('/^[A-Z].*[A-Z]$/' , ', $subject), ' <br/> ';//The regular expression is that the match contains only \w elements, $subject starts with Q, conforms to [A-z], and ends with M, also matches [A-z]: Unable to match \n//output "snsgou.com is loveing you "echo preg_replace ('/^[a-z].*[a-z]$/s '," ', $subject), ' <br/> ';//This modifier s, that is. can match \ n, so the whole sentence matches, output empty//Output "" Echo preg_replace ('/^[a-z].*[a-z]$/m ', ', $subject), ' <br/> ';//The modifier is used here to match \ n as a multiline independent. Also equivalent to:/* $preg _m = preg_replace ('/^[a-z].*[a-z]$/m ', ' ', $subject); $p = '/^[a-z].*[a-z]$/'; $a = preg_replace ($p, ', ' Snsgou.com '), $b = Preg_replace ($p, ' ', ' is '), $c = Preg_replace ($p, "', ' loving '); $d = Preg_replace ($p, ' ', ' you '); $preg _m = = = $a. $b. $c. $d; *///output "snsgou.com"?>

In the future when you use PHP to crawl a site content, and with regular batch replacement, there is always no way to avoid ignoring the obtained content contains newline characters, so you must pay attention when using regular replacement.

PHP Regular Match execution function

PHP regular substitution can use a modifier e, which represents Eval () to perform a function that matches the content.

<?php$subject= ' Chan Yunlai PHP blog URL: http://www.qianYUNlai.com/';//convert the above URL to lowercase echo preg_replace ('/(http\:[\/\w\.\-]+\/)/E ', ' Strtolower ("$") ', $subject);//After using the modifier e, you can execute PHP function strtolower ()/output "Chan Yunlai PHP Blog URL: http://blog.snsgou.com/ "?>

According to the above code, although the matched function strtolower () is inside the quotation marks, it will still be executed by eval ().

Regular substitution matching variable backward reference

If you are familiar with JavaScript, be sure to ... such as backward references are familiar, and in PHP these can also be used as backward reference parameters. In PHP, you can also use \1 \\1 to represent backward references.

The concept of backward referencing is to match a large fragment, in which the inside of the regular expression is cut into several small matching elements, and each matched element is replaced by a backward reference in the parentheses sequence.

<?php$subject= ' Chan Yunlai PHP blog URL: http://blog.snsgou.com/, have you Yun-lai? '; Echo preg_replace ('/.+ (http\:[\w\-\/\. +\/) [^\w\-\!] + ([\w\-\!] +). +/', ' $ ', $subject); Echo preg_replace ('/.+ (http\:[\w\-\/\. +\/) [^\w\-\!] + ([\w\-\!] +). +/', ' \1 ', $subject); Echo preg_replace ('/.+ (http\:[\w\-\/\.] +\/) [^\w\-\!] + ([\w\-\!] +). +/', ' \\1 ', $subject); Usually use this echo ' <br/> ';//The above three are output "http://blog.snsgou.com/" echo preg_replace ('/^ (. +) URL: (http\:[\w\-\/\.) +\/) [^\w\-\!] + ([\w\-\!] +). +$/', ' column:$1<br> URL:$2<br> trademark: $ $ ', $subject);/* column: Chan Yunlai PHP Blog URL: http://blog.snsgou.com/trademark: yun-lai*/ echo ' <br/> ';//brackets in brackets, outer brackets count echo preg_replace ('/^ (. +) URL: (http\:[\w\-\/\.] +\/) [^\w\-\!] + ([\w\-\!] +). +) $/', ' original:$1<br> column:$2<br> URL:$3<br> trademark: $4 ', $subject);/* Original: Chan Yunlai PHP Blog URL: http://blog.snsgou.com /, Have you Yun-lai? Section: Chan Yunlai PHP Blog URL: http://blog.snsgou.com/trademark:yun-lai*/?>

php function preg_replace () regular replace all strings that match the criteria

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.