Removing Redundant Rows

I am looking for something like trim (), but within a string. Users sometimes put 2, 3, 4 or more lines after they print, I need to sanitize this entry.

Input example

i like cats


my cat is happy
i love my cat



hope you have a nice day

Required conclusion

i like cats

my cat is happy
i love my cat

hope you have a nice day

I don't see anything inline, and replacing a string will require many iterations to do the job. Before I pick up a small recursive line, I want to see what other suggestions you had.

I have a strange feeling that there is a regular expression for this.

+5
source share
5 answers

Finally, he managed to get it, which requires preg, so you use the PCRE version in php, and you also need the replacement string \ n \ n so as not to erase all the ends of the lines except one:

  $body = preg_replace("/\n\n+/", "\n\n", $body);

, .

+3
function str_squeeze($body) {
    return preg_replace("/\n\n+/", "\n\n", $body);
}
+10

? , 100k, ( - /\n+/ \n)

, , , , , , .

, , .

+3

:

preg_replace('/(?:\r\n|[\r\n]){2,}/', "\n\n", $str)
+3

The following regular expression should delete multiple lines, ignoring individual line breaks that match your definition:

ereg_replace("\n\n+", "\n\n", $string);

You can test it with this PHP regular expression testing tool , which is very handy (but doesn't seem to be perfect for PHP).

[EDIT] Fixed the 'to' value because they did not seem to work. I have to admit that I just checked the regex in the web tool .;)

+2
source

All Articles