PHP 的 preg_replace 正则表达式匹配多行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2240348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP's preg_replace regex that matches multiple lines
提问by Jeroen Beerstra
How do I create a regex that takes into account that the subject consists of multiple lines?
如何创建考虑到主题由多行组成的正则表达式?
The "m" modifier for one does not seem to work.
" m" 修饰符似乎不起作用。
回答by Bart Kiers
Maxwell Troy Milton King is right, but since his answer is a bit short, I'll post this as well and provide some examples to illustrate.
Maxwell Troy Milton King 是对的,但由于他的回答有点简短,我也会发布此内容并提供一些示例来说明。
First, the .meta character by default does NOT match line breaks. This is true for many regex implementations, including PHP's flavour. That said, take the text:
首先,.默认情况下元字符不匹配换行符。这适用于许多正则表达式实现,包括 PHP 的风格。话虽如此,请看正文:
$text = "Line 1\nLine 2\nLine 3";
and the regex
和正则表达式
'/.*/'
then the regex will only match Line 1. See for yourself:
那么正则表达式只会匹配Line 1。你自己看:
preg_match('/.*/', $text, $match);
echo $match[0]; // echos: 'Line 1'
since the .*"stops matching" at the \n(new line char). If you want to let it match line breaks as well, append the s-modifier (aka DOT-ALL modifier) at the end of your regex:
因为.*在\n(新行字符)处“停止匹配” 。如果您还想让它匹配换行符,请在正则表达式的末尾附加 s-修饰符(又名 DOT-ALL 修饰符):
preg_match('/.*/s', $text, $match);
echo $match[0]; // echos: 'Line 1\nLine 2\nLine 3'
Now about the m-modifier (multi-line): that will let the ^match not only the start of the input string, but also the start of each line. The same with $: it will let the $match not only the end of the input string, but also the end of each line.
现在关于 m 修饰符(多行):它不仅可以^匹配输入字符串的开头,还可以匹配每行的开头。与$:相同,它$不仅会让匹配输入字符串的结尾,还会匹配每一行的结尾。
An example:
一个例子:
$text = "Line 1\nLine 2\nLine 3";
preg_match_all('/[0-9]$/', $text, $matches);
print_r($matches);
which will match only the 3 (at the end of the input). But:
它将仅匹配 3(在输入的末尾)。但:
but enabling the m-modifier:
但启用 m 修饰符:
$text = "Line 1\nLine 2\nLine 3";
preg_match_all('/[0-9]$/m', $text, $matches);
print_r($matches);
all (single) digits at the end of each line ('1', '2' and '3') are matched.
每行末尾的所有(单个)数字(“1”、“2”和“3”)都匹配。
回答by ziya
Try the 's' modifier. Meaning 'treat as if a single line'.
试试's' 修饰符。意思是“像一行一样对待”。
'm' enables the use of ^ and $ line beginnings and endings to be used.
'm' 允许使用 ^ 和 $ 行开始和结束。

