简体   繁体   English

PHP合并一行中的换行符数量并在必要时减少它?

[英]PHP Merge the number of line-breaks in a row and reduce it if necessary?

I have a textarea where users can submit a post in PHP. 我有一个textarea,用户可以用PHP提交帖子。 I want to check the number of line breaks in a row and reduce it if necessary, for example. 我想检查一行中的换行符数量,并在必要时减少它,例如。

ORIGINAL: 原版的:

Hello\n
\n\n\n\n\n\n\n\n\n\n\n\n\n
Goodbye

WHAT I WANT IN THE END: 我到底想要什么:

Hello\n
\n
Goodbye

So basically I want a maximum of 2 line breaks in a row . 所以基本上我想连续最多2个换行符 How can I achieve this in PHP? 我怎样才能在PHP中实现这一点?

Thanks for any help. 谢谢你的帮助。

PCRE:

preg_replace('/\n{3,}/m', "\n\n", $text);

I'd do a loop replace 我会做一个循环替换

$data = "Hello\n\n\n\n\n\n\n\n\n\n\n\n\nGoodbye";
while(($newdata = str_replace("\n\n\n", "\n\n", $data) != $data){
    $data = $newdata;
}

This will replace 3 \\n by 2 \\n as long as there are possibilities. 只要有可能,这将取代3 \\ n乘以2 \\ n。

Keep in mind you could need to replace all \\r too with \\n because your input can never be perfect. 请记住,你可能需要用\\ n替换所有\\ r \\ n,因为你的输入永远不会是完美的。 This also doesn't take into account the possibilies of whitespaces inbetween the \\n. 这也没有考虑到\\ n之间的空格的可能性。

To add to tandu's response, this variation accounts for carriage-returns as well: 要添加到tandu的响应,此变体也会考虑回车:

preg_replace(array('/\r/m','/\n{3,}/m'), array("\n","\n\n"), $text);

First convert \\r 's to \\n 's so that \\r\\n sequences are reduced to \\n\\n . 首先将\\r转换为\\n ,以便将\\r\\n序列缩减为\\n\\n Then the filter for sequential \\n 's finishes the job. 那么对于连续的过滤器\\n的完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM