Home  >  Article  >  Backend Development  >  How to implement regular replacement content in php

How to implement regular replacement content in php

藏色散人
藏色散人Original
2021-03-02 09:23:382382browse

php method to implement regular content replacement: first create a PHP sample file; then define a set of strings; finally pass "preg_replace('/http\:\/\/www\...\.com \/\_blog\//'...)" regular expression can replace the content.

How to implement regular replacement content in php

#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.

PHP function preg_replace() regular replacement of all qualified strings

PHP preg_replace() regular replacement, different from JavaScript regular replacement, PHP preg_replace() The default is to replace all elements whose symbols match the condition.

preg_replace (正则表达式, 替换成, 字符串, 最大替换次数【默认-1,无数次】, 替换次数)

The regular expressions in most languages ​​​​are similar, but there are also subtle differences.

PHP Regular Expression

##? Matches the preceding subexpression zero or one time. For example, "do(es)?" can match "does" or "do" in "does". ? is equivalent to {0,1} .{n}n is a non-negative integer. Matches a certain number of n times. For example, "o{2}" cannot match "Bob" "o", but can match two o's in "food". {n,}n is a non-negative integer. Match at least n times. For example, "o{2,}" cannot match the "o" in "Bob", but it can match all o's in "foooood". "o{1,}" is equivalent to "o ". "o{0, }" is equivalent to "o*". {n,m}m and n are non-negative integers, where n<=m. At least Match n times and at most m times. For example, "o{1,3}" will match the first three o's in "fooooood". "o{0,1}" is equivalent to "o?". Please note that in There cannot be a space between the comma and the two numbers. ?When this character is immediately followed by any other limiter (*, ,?, {n} , {n,}, {n,m}), the matching mode is non-greedy. The non-greedy mode matches as few of the searched characters as possible, while the default greedy mode matches as many of the searched characters as possible String. For example, for the string "oooo", "o?" will match a single "o", and "o" will match all "o"s. .Point Matches any single character except "\n". To match any character including "\n", use a pattern like "[\s\S]". (pattern) Match pattern and get this match. The obtained match can be obtained from the generated Matches collection, using the SubMatches collection in VBScript, and using the $0...$9 attribute in JScript . To match parentheses characters, use "\(" or "\)". (?:pattern) Matches pattern but does not obtain the matching result, which means that this is a non-acquisition match and is not stored for later use. This is useful when combining parts of a pattern using the or character "(|)". For example, "industr(?:y|ies)" is a simpler expression than "industry|industries". (?=pattern)(?!pattern)##(?<=pattern)Reverse positive pre-check##(? is similar to forward negative pre-check, but in the opposite direction. For example, "(?x|y Matches x or y. For example, "z|food" matches "z" or "food". "(z|f)ood" matches "zood" or "food". [xyz]Character collection. Matches any one of the characters contained. For example, "[abc]" would match the "a" in "plain".
Regular characters Regular explanation
\ Mark the next character as a special character , or a literal character, or a backreference, or an octal escape character. For example, "\n" matches the character "n". "\\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".
^ matches the beginning of the input string. If set The Multiline property of the RegExp object, ^ also matches the position after "\n" or "\r".
$ matches the end position of the input string. If When the Multiline property of the RegExp object is set, $ also matches the position before "\n" or "\r".
* matches the preceding subexpression zero times or multiple times. For example, zo* can match "z" and "zoo". * is equivalent to {0,}.
matches the previous sub Expression one or more times. For example, "zo" can match "zo" and "zoo", but not "z". Equivalent to {1,}.
Forward positive pre-lookup, matches the search string at the beginning of any string matching pattern. This is a non-fetch match, that is, the match does not need to be fetched for later use. For example, "Windows(?=95|98|NT|2000)" can match "Windows" in "Windows2000", but cannot match "Windows" in "Windows3.1". Prefetching does not consume characters, that is, after a match occurs, the search for the next match begins immediately after the last match, rather than starting after the character containing the prefetch.
Forward negative pre-lookup, matches the search string at the beginning of any string that does not match pattern. This is a non-fetch match, that is, the match does not need to be fetched for later use. For example, "Windows(?!95|98|NT|2000)" can match "Windows" in "Windows3.1", but cannot match "Windows" in "Windows2000".
is similar to forward positive pre-check, but in the opposite direction. For example, "(?<=95|98|NT|2000)Windows" can match "Windows" in "2000Windows", but cannot match "Windows" in "3.1Windows".
Reverse negative pre-check
[^xyz] Negative value character set. Matches any character not included. For example, "[^abc]" would match "plin" in "plain".
[a-z] Character range. Matches any character within the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z". Note: Only when the hyphen is inside the character group and appears between two characters, it can represent the range of characters; if it appears at the beginning of the character group, it can only represent the hyphen itself.
[^a-z] Negative character range. Matches any character not within the specified range. For example, "[^a-z]" matches any character that is not in the range "a" through "z".
\b Matches a word boundary, which refers to the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\B Matches non-word boundaries. "er\B" can match the "er" in "verb", but not the "er" in "never".
\cx Matches the control character specified by x. For example, \cM matches a Control-M or carriage return character. The value of x must be one of A-Z or a-z. Otherwise, treat c as 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 form feed character. Equivalent to \x0c and \cL.
\n Matches a newline character. Equivalent to \x0a and \cJ.
\r Matches a carriage return character. Equivalent to \x0d and \cM.
\s Matches any whitespace characters, including spaces, newlines, tabs, form feeds, Chinese full-width spaces, etc. 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 character. Equivalent to \x0b and \cK.
\w Matches any word character including an underscore. Equivalent to "[A-Za-z0-9_]".
\W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\xn Matches n, where n is the hexadecimal escape value. The hexadecimal escape value must be exactly two digits long. 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 match obtained. For example, "(.)\1" matches two consecutive identical characters.
\n Identifies an octal escape value or a backreference. If \n is preceded by at least n fetched subexpressions, n is a backward reference. Otherwise, if n is an octal number (0-7), then n is an octal escape value.
\nm Identifies an octal escape value or a backreference. If there are at least nm get subexpressions before \nm, nm is a backward reference. If \nm is preceded by at least n acquisitions, n is a backward reference followed by the literal m. If none of the previous conditions are met, and if n and m are both octal numbers (0-7), then \nm will match the octal escape value nm.
\nml If n is an octal number (0-7), and m and l are both octal numbers (0-7), match the octal escape Value nml.
\un Matches n, where n is a Unicode character represented by four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©).

上表是正则表达式比较全面的解释,而商标中的正则字符都有特殊含义,已经不再代表原字符含义。如正则表达式中“+”不代表加号,而是代表匹配一次或多次。而如果想要让“+”表示加号,则需要在其前面加上“\”转义,也就是用“\+”表示加号。

【推荐学习:《PHP视频教程》】

1+1=2  正则表达式是: 1\+1=2
而正则表达式 1+1=2 可以代表,多个1=2,即:
11=2     正则表达式:1+1=2
111=2    正则表达式:1+1=2
1111=2   正则表达式:1+1=2
……

也就是说所有正则字符都有特定含义,如果需要再用来表示原字符含义,就需要在前面加“\”转义,即使非正则字符,用“\”转义也是没有问题的。

1+1=2  正则表达式也可以是: \1\+\1\=\2
对所有字符都转义,但是这种不建议使用。 

而正则表达式必须要使用定界符包围起来,在JavaScript中定界符是“/”,而在PHP中,比较常见的是用“/”定界,也可以用“#”定界,而且外面还需要用引号包围起来。

如果正则表达式包含这些定界符,您就需要对这些字符进行转义。

 

PHP 正则表达式定界符

大多数语言的正则表达式都是由“/”作为定界符的,而在PHP中,还可以使用“#”定界,如果字符串中包含大量“/”字符,在使用“/”定界的时候,就需要对这些“/”转义,而使用“#”就不需要转义,更简洁。

<?php
$subject=&#39;钱运来PHP博客的网址是 http://blog.snsgou.com/_blog/ ,你能把这个网址替换成正确的网址吗?&#39;;

// 上面的要求就是把 http://blog.snsgou.com/_blog 替换成 http://blog.snsgou.com/

// . : - 都是正则符号,所以需要转义,而 / 是定界符,如果字符串中包含 / 定界符,就需要转义

echo preg_replace(&#39;/http\:\/\/www\.qianyunlai\.com\/\_blog\//&#39;, &#39;http://blog.snsgou.com/&#39;, $subject);

echo &#39;<br />&#39;;

// 在 #作为定界符,/ 就不再是定界符的含义,就不需要转义了。
echo preg_replace(&#39;#http\://www\.qianyunlai\.com/\_blog/#&#39;, &#39;http://blog.snsgou.com/&#39;, $subject);

// 上面两条输出结果都一样,【钱运来PHP博客的网址是 http://blog.snsgou.com/,你能把这个网址替换成正确的网址吗?】

?>

通过上面的两条PHP 正则替换代码我们可以发现,如果正则语句中包含大量“/”,无论使用“/” 还是 “#”做定界符都是可以的,但是使用“#”能让代码看起来更简洁。但还是建议您保持使用“/”作为定界符,因为在JavaScript等语言中,只能使用“/”作为定界符,这样写起来可以形成习惯,贯通于其他语言中。

PHP 正则表达式修饰符

修饰符被放在PHP正则表达式定界符“/”之后,在正则表达式尾部引号之前。

i 忽略大小写,匹配不考虑大小写

m 多行独立匹配,如果字符串不包含[\n]等换行符就和普通正则一样。

s 设置正则符号 . 可以匹配换行符[\n],如果没有设置,正则符号.不能匹配换行符\n。

x 忽略没有转义的空格

eval() 对匹配后的元素执行函数。

A 前置锚定,约束匹配仅从目标字符串开始搜索

D 锁定$作为结尾,如果没有D,如果字符串包含[\n]等换行符,$依旧依旧匹配换行符。如果设置了修饰符m,修饰符D 就会被忽略。

S 对非锚定的匹配进行分析

U 非贪婪,如果在正则字符量词后加“?”,就可以恢复贪婪

X 打开与perl 不兼容附件

u 强制字符串为UTF-8编码,一般在非UTF-8编码的文档中才需要这个。建议UTF-8环境中不要使用这个。

如果您熟悉JavaScript 的正则表达式,或许一定熟悉JavaScript 正则表达式的修饰符“g”,代表匹配所有符合条件的元素。而在PHP 正则替换中,是匹配所有符号条件的元素,所以不存在JavaScript 修饰符“g”。

PHP 正则中文和忽略大小写

PHP preg_replace() 是区分大小写的,同时只能匹配ASCII编码内的字符串,如果需要匹配不区分大小写和中文等字符需要添加相应的修饰符 i 或 u。

<?php
$subject=&#39;钱运来PHP博客网址:http://www.QIanyunlai.com/&#39;;

// 大小写不同,输出【钱运来PHP博客网址:http://www.QIanyunlai.com/】
echo preg_replace(&#39;/QIAN/&#39;, &#39;qian&#39;, $subject);
echo &#39;<br />&#39;;

// 忽略大小写,执行替换输出【钱运来PHP博客网址:http://blog.snsgou.com/】
echo preg_replace(&#39;/QIAN/i&#39;, &#39;qian&#39;, $subject);
echo &#39;<br />&#39;;

// 强制 UTF-8中文,执行替换,输出【钱运来PHP博客:http://www.QIanyunlai.com/】
echo preg_replace(&#39;/网址/u&#39;, &#39;&#39;, $subject);
?>

大小写和中文在PHP中都是敏感的,但是在JavaScript正则中,只对大小写敏感,忽略大小写也是通过修饰符 i 作用的,但是JavaScript 不需要告知是否是UTF-8中文等特殊字符,直接可以匹配中文。

PHP 正则换行符实例

PHP 正则表达式在遇到换行符时,会将换行符当做字符串中间一个普通字符。而通用符号.不能匹配\n,所以遇到带有换行符的字符串正则会有很多要点。

<?php
$subject="snsgou.com\nIS\nLOVING\nYOU";

// 想要把上面$subject 替换成snsgou.com

echo preg_replace(&#39;/^[A-Z].*[A-Z]$/&#39;, &#39;&#39;, $subject), &#39;<br />&#39;;
// 这个正则表达式是,匹配只包含\w的元素,$subject 是以q开头,符合[A-Z],而且结尾是m,也符合[A-Z]。.无法匹配\n
// 输出【snsgou.com IS LOVEING YOU】

echo preg_replace(&#39;/^[A-Z].*[A-Z]$/s&#39;, &#39;&#39;, $subject), &#39;<br />&#39;;
// 这个用修饰符s,也就是 . 可以匹配 \n 了,所以整句匹配,输出空
// 输出【】

echo preg_replace(&#39;/^[A-Z].*[A-Z]$/m&#39;, &#39;&#39;, $subject), &#39;<br />&#39;;
// 这里使用了修饰符,将\n作为多行独立匹配。也就等价于:
/*
$preg_m = preg_replace(&#39;/^[A-Z].*[A-Z]$/m&#39;, &#39;&#39;, $subject);

$p = &#39;/^[A-Z].*[A-Z]$/&#39;;
$a = preg_replace($p, &#39;&#39;, &#39;snsgou.com&#39;);
$b = preg_replace($p, &#39;&#39;, &#39;IS&#39;);
$c = preg_replace($p, &#39;&#39;, &#39;LOVING&#39;);
$d = preg_replace($p, &#39;&#39;, &#39;YOU&#39;);

$preg_m === $a . $b . $c . $d;
*/
// 输出【snsgou.com】
?>

以后您在使用PHP 抓取某个网站内容,并用正则批量替换的时候,总无法避免忽略获取的内容包含换行符,所以在使用正则替换的时候一定要注意。

PHP 正则匹配执行函数

PHP 正则替换可以使用一个修饰符e,代表 eval() 来执行匹配后的内容某个函数。

<?php
$subject=&#39;钱运来PHP博客网址:http://www.qianYUNlai.com/&#39;;

// 将上面网址转为小写

echo preg_replace(&#39;/(http\:[\/\w\.\-]+\/)/e&#39;, &#39;strtolower("$1")&#39;, $subject);
// 使用修饰符e之后,就可以对匹配的网址执行PHP 函数 strtolower() 了
// 输出 【钱运来PHP博客网址:http://blog.snsgou.com/】
?>

根据上面代码,尽管匹配后的函数 strtolower() 在引号内,但是依旧会被eval()执行。

正则替换匹配变量向后引用

如果您熟悉JavaScript,一定对$1 $2 $3 …… 等向后引用比较熟悉,而在 PHP 中这些也可以被当作向后引用参数。而在PHP中,还可以使用 \1 \\1 来表示向后引用。

向后引用的概念就是匹配一个大片段,这个正则表达式内部又被用括号切割成若干小匹配元素,那么每个匹配元素就被按照小括号序列用向后引用代替。

<?php
$subject=&#39;钱运来PHP博客网址:http://blog.snsgou.com/,你yun-lai了吗?&#39;;

echo preg_replace(&#39;/.+(http\:[\w\-\/\.]+\/)[^\w\-\!]+([\w\-\!]+).+/&#39;, &#39;$1&#39;, $subject);
echo preg_replace(&#39;/.+(http\:[\w\-\/\.]+\/)[^\w\-\!]+([\w\-\!]+).+/&#39;, &#39;\1&#39;, $subject);
echo preg_replace(&#39;/.+(http\:[\w\-\/\.]+\/)[^\w\-\!]+([\w\-\!]+).+/&#39;, &#39;\\1&#39;, $subject); // 通常用这个
echo &#39;<br />&#39;;
// 上面三个都是输出 【http://blog.snsgou.com/】

echo preg_replace(&#39;/^(.+)网址:(http\:[\w\-\/\.]+\/)[^\w\-\!]+([\w\-\!]+).+$/&#39;, &#39;栏目:$1<br>网址:$2<br>商标:$3&#39;, $subject);
/*
栏目:钱运来PHP博客
网址:http://blog.snsgou.com/
商标:yun-lai
*/
echo &#39;<br />&#39;;

// 括号中括号,外面括号先计数
echo preg_replace(&#39;/^((.+)网址:(http\:[\w\-\/\.]+\/)[^\w\-\!]+([\w\-\!]+).+)$/&#39;, &#39;原文:$1<br>栏目:$2<br>网址:$3<br>商标:$4&#39;, $subject);
/*
原文:钱运来PHP博客网址:http://blog.snsgou.com/,你yun-lai了吗?
栏目:钱运来PHP博客
网址:http://blog.snsgou.com/
商标:yun-lai
*/
?>

 

The above is the detailed content of How to implement regular replacement content in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn