正则表达式与 php 的 preg_match 一起使用以查找换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6206343/
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
Regex for use with php's preg_match to find a newline
提问by Ed Fearon
I'm fairly new/rusty with regular expressions. I'm collecting a block of text from a textarea element and I want to check to see if the person who filled it used any paragraphs, amongst other things.
我对正则表达式相当新/生疏。我正在从 textarea 元素中收集一段文本,我想检查填写它的人是否使用了任何段落等。
I'm using the following and I know it's wrong. Any help would be appreciated.
我正在使用以下内容,我知道这是错误的。任何帮助,将不胜感激。
preg_match('/\r\n|\n|\r/', $_GET['text']);
采纳答案by mario
Your regex is not wrong. But for detecting paragraphs you will want to look for two consecutive newlines:
你的正则表达式没有错。但是为了检测段落,您需要查找两个连续的换行符:
preg_match('/(\r?\n){2}/'
The carriage return \r
is optional, and I would just check for \n
newline as most platforms treat that as linebreak. Obviously this check will fail if the submitted text is just a single line without paragraphs or newlines.
回车\r
是可选的,我只会检查\n
换行符,因为大多数平台将其视为换行符。显然,如果提交的文本只是没有段落或换行符的单行,则此检查将失败。
Alternatively you could also probe for two newlines with any sortof whitespace in between:
或者,您也可以探测两个换行符,中间有任何类型的空格:
preg_match('/(\s*\n){2}/'
回答by seriousdev
Assuming:
假设:
This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.
And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another.
这是一个段落。这是一个段落。这是一个段落。这是一个段落。这是一个段落。这是一个段落。这是一个段落。这是一个段落。这是一个段落。
这是另一个。这是另一个。这是另一个。这是另一个。这是另一个。这是另一个。这是另一个。这是另一个。这是另一个。这是另一个。
You could just do:
你可以这样做:
if (str_replace("\r\n\r\n", '', $str) != $str)
// the input contains at least two paragraphs