Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove new lines from string and replace with one empty space

Tags:

string

regex

php

$string = " put returns between paragraphs  for linebreak add 2 spaces at end  "; 

Want to remove all new lines from string.

I've this regex, it can catch all of them, the problem is I don't know with which function should I use it.

/\r\n|\r|\n/ 

$string should become:

$string = "put returns between paragraphs for linebreak add 2 spaces at end "; 
like image 987
James Avatar asked Sep 21 '10 13:09

James


People also ask

How do you remove all new lines from a 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.

Does trim remove new lines?

trim method removes any line breaks from the start and end of a string. It handles all line terminator characters (LF, CR, etc). The method also removes any leading or trailing spaces or tabs. The trim() method doesn't change the original string, it returns a new string.


1 Answers

You have to be cautious of double line breaks, which would cause double spaces. Use this really efficient regular expression:

$string = trim(preg_replace('/\s\s+/', ' ', $string)); 

Multiple spaces and newlines are replaced with a single space.

Edit: As others have pointed out, this solution has issues matching single newlines in between words. This is not present in the example, but one can easily see how that situation could occur. An alternative is to do the following:

$string = trim(preg_replace('/\s+/', ' ', $string)); 
like image 77
jwueller Avatar answered Sep 20 '22 06:09

jwueller