I want to replace newlines (\r\n) with space, but I want to keep the blank lines. In other words, I want to replace \r\n with ' ', if \r\n is not preceded by another \r\n. For example:
line 1
line 2
line 3
line 4
Shold end up as...
line 1
line 2 line 3 line 4
But not as "line 1 line 2 line 3 line 4", which is what I'm doing right now with this
preg_replace("/\r\n/", " ", $string);
Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text.
If you aren't firing vim or sed for some other use, cat actually has an easy builtin way to collapse multiple blank lines, just use cat -s .
To remove extra whitespace (i.e. more than one consecutive spaces), use the same regex \s+ but replace the found matches with a single space character.
Method 2: Use the strip() Function to Remove a Newline Character From the String in Python. The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.
Try this:
(?<!\n)\n(?!\n)
Of course, you can change \n
to whatever you need.
Working example: http://ideone.com/dF5L9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With