s/(?=\s)\s*?(?:(\n\n)|(?=\S))/$1||" "/eg; #### s/ (?=\s) # Be sure we will match some whitespace \s*? # Match as little whitespace as we can (?: # To either: ( # Capture blank line...? (?:\r\n?|\n\r?) # First line ending. \s*? # Any whitespace on the line. (?:\r\n?|\n\r?) # Second line ending. ) # End capture. | # or (?=\S) # End of the whitespace. ) # / $1 || " " # Either the blank line or a space. /egx;