简体   繁体   中英

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. 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 . How can I achieve this in 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.

Keep in mind you could need to replace all \\r too with \\n because your input can never be perfect. This also doesn't take into account the possibilies of whitespaces inbetween the \\n.

To add to tandu's response, this variation accounts for carriage-returns as well:

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 . Then the filter for sequential \\n 's finishes the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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