Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将两条以上的新线减少为一条_Php_Regex - Fatal编程技术网

Php 将两条以上的新线减少为一条

Php 将两条以上的新线减少为一条,php,regex,Php,Regex,将两条以上的新线路缩减为一条的正确方法是什么 preg_replace('/[\n]{2,}/', "\n", "Hi,\nHow are you?\n\n\nI am just testing"); 返回: Hi, How are you? I am just testing 同时,预期结果是: Hi, How are you? I am just testing 目标是重新格式化电子邮件文本,并将任何大于3的空格更改为1 谢谢 也许这有帮助 $string = str_replace

将两条以上的新线路缩减为一条的正确方法是什么

preg_replace('/[\n]{2,}/', "\n", "Hi,\nHow are you?\n\n\nI am just testing");
返回:

Hi,
How are you?
I am just testing
同时,预期结果是:

Hi,
How are you?

I am just testing
目标是重新格式化电子邮件文本,并将任何大于3的空格更改为1

谢谢

也许这有帮助

$string = str_replace("   ", "\n", $string);


我不知道你的困惑是什么。。。将两个或多个
\n
替换为一个
\n
将导致单行中断,这就是您得到的结果。从你的例子来看,你似乎想要一个双线中断。(换行符,然后是空行,然后是另一个换行符。)


注意,我还删除了正则表达式中
[]
周围不必要的
\n

只是对先前答案的改进。 从你的例子来看,你似乎想要一个双线中断。(换行符,然后是空行,然后是另一个换行符)

{3,}因为不需要匹配/替换两个或更少的\n。
注意:我发布了一个新的答案,因为我还没有名声添加评论。

我想你必须澄清你的问题。如您所指定,三个换行符将减少为一个。您的“预期”输出将三个换行减少为两个。那你想要什么?这不正是它的功能吗?在您的预期结果中,有不止一条新行。看来实际回报是你想要的?
$string = str_replace("   ", " ", $string);
preg_replace('/\n{2,}/', "\n\n", "Hi,\nHow are you?\n\n\nI am just testing");
preg_replace('/\n{3,}/', "\n\n", "Hi,\nHow are you?\n\n\nI am just testing");