368
$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 ";
2
  • 2
    If you're doing thousands of replacements, avoid using preg_replace. It is almost twice as slow as str_replace. Commented Jun 20, 2014 at 13:23
  • You might find s($str)->normalizeLineEndings('') helpful, as found in this standalone library. It will remove not only LF, CR and CRLF, but also any Unicode newline. Commented Jul 26, 2016 at 23:58

20 Answers 20

699

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Before you use this solution, see my answer below and the comments to my answer. This solution may not work as you expect.
I was searching for a solution to remove/replace all whitespaces but not (double) spaces. This is the regex that did it: /(?![ ])\s+/
\s matches any whitespace including space, tab, newline, carriage return. To match newlines you need \r?\n which is a newline optionally preceded by a carriage return.
213

A few comments on the accepted answer:

The + means "1 or more". I don't think you need to repeat \s. I think you can simply write '/\s+/'.

Also, if you want to remove whitespace first and last in the string, add trim.

With these modifications, the code would be:

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

1 Comment

You're right; /\s\s+/ would fail to match the linefeed in foo\nbar.
128

Just use preg_replace()

$string = preg_replace('~[\r\n]+~', '', $string);

You could get away with str_replace() on this one, although the code doesn't look as clean:

$string = str_replace(array("\n", "\r"), '', $string);

See it live on ideone

5 Comments

OP wants a space between "paragraphs" and "for". If you just remove the newline characters, there won't be one.
@Daniel I got the idea that the OP wanted to remove all newline characters, period.
I had to use "\\n" like this: $row->title = str_replace("\\n", '', $row->title);
What do the '~' in the regular expressions mean?
@Vineet It's just a delimiter denoting start and end of the regex
30
$string = str_replace(array("\n", "\r"), ' ', $string);

1 Comment

This doesn't do exactly what the OP wants though, since this is the same as elusive's answer and it's not removing the \r characters
28

I'm not sure if this has any value against the already submitted answers but I can just as well post it.

// Create an array with the values you want to replace
$searches = array("\r", "\n", "\r\n");

// Replace the line breaks with a space
$string = str_replace($searches, " ", $string);

// Replace multiple spaces with one
$output = preg_replace('!\s+!', ' ', $string);

3 Comments

I like this solution based on the OP. preg_replace can be slow. But str_replace with an array is a great solution. In theory, the 3rd option in $searches isn't needed as those characters would already have been replaced. But you could move it to the front to strip them first.
I started php in 2023 & I had my answer ready in 2015. :) basically I write qry line by line for code readability but I also return qry for debug in response so In response I got "/r /n" so I need qry in pretty format in response in that scenario its perfact thank you
put \r\n as first element of the array to prevent double spaces also, use one-liner to prevent casting one-time used resources into variable
16

You should use str_replace for its speed and using double quotes with an array

str_replace(array("\r\n","\r"),"",$string);

2 Comments

I might be wrong but this code does not remove new line char on Unix systems because on those systems new line is just \n and not \r\n moreover I think the OP is asking to put a single space in place of new lines
@MarcoDemaio, just add "\n", "\n\r" to array.
13

Escape sequence \R matches a generic newline

that is, anything considered a linebreak sequence by Unicode. This includes all characters matched by \v (vertical whitespace), and the multi character sequence \x0D\x0A...

$string = preg_replace('/\R+/', " ", $string);

In 8-bit non-UTF-8 mode \R is equivalent to the following: (?>\r\n|\n|\x0b|\f|\r|\x85)... pcre.org

Regex101 Demo

1 Comment

Anton please check, if my edit is ok! Added some further information.
10

Line breaks in text are generally represented as:

\r\n - on a windows computer

\r - on an Apple computer

\n - on Linux

//Removes all 3 types of line breaks

$string = str_replace("\r", "", $string);

$string = str_replace("\n", "", $string);

Comments

7

PCRE regex replacements can be done using preg_replace: http://php.net/manual/en/function.preg-replace.php

$new_string = preg_replace("/\r\n|\r|\n/", ' ', $old_string);

Would replace new line or return characters with a space. If you don't want anything to replace them, change the 2nd argument to ''.

1 Comment

The preg functions use PCRE, not POSIX, regular expressions. There are ereg functions that use POSIX, but they are now deprecated.
5

Use this:

replace series of newlines with an empty string:

$string = preg_replace("/[\\n\\r]+/", "", $string);

or you probably want to replace newlines with a single space:

$string = preg_replace("/[\\n\\r]+/", " ", $string);

2 Comments

Please format your code properly. This is done by indenting the relevant line by four spaces.
That's why I use single quotes so I don't need to escape those characters. \\n looks terrible. \\\\ to match a single backslash is just awful.
5

Many of these solutions didn't work for me. This did the trick though:-

$svgxml = preg_replace("/(*BSR_ANYCRLF)\R/",'',$svgxml);

Here is the reference:- PCRE and New Lines

1 Comment

This is 100% the better solution. I was having problems with strange line breaks that I just wasn't able to catch with the usual suspects. I tried replacing \n, \036, \n\r, \025, \n and \r... none worked. This solution however works like a charm!
4

Whats about:

$string = trim( str_replace( PHP_EOL, ' ', $string ) );

This should be a pretty robust solution because \n doesn't work correctly in all systems if i'm not wrong ...

3 Comments

This doesn't seem to replace \r but just \n: ideone.com/28KPcb
As mentioned in the manual PHP_EOL contains the correct 'End Of Line' symbol for the current platform. If you importing strings from other platforms or you have just bad formatted strings this may break.
If you have a pretty closed environment this seems like the most elegant solution to me because its platform independent and probably pretty performant … if you have more broad input like import/export scenarios you probably should use a regex solution.
3

I was surprised to see how little everyone knows about regex.

Strip newlines in php is

$str = preg_replace('/\r?\n$/', ' ', $str);

In perl

$str =~ s/\r?\n$/ /g;

Meaning replace any newline character at the end of the line (for efficiency) - optionally preceded by a carriage return - with a space.

\n or \015 is newline. \r or \012 is carriage return. ? in regex means match 1 or zero of the previous character. $ in regex means match end of line.

The original and best regex reference is perldoc perlre, every coder should know this doc pretty well: http://perldoc.perl.org/perlre.html Note not all features are supported by all languages.

2 Comments

This solution didn't work for me but as mentioned, I will need to read more to produce the actual solution. I was surprised this didn't work.
@AdamWhateverson No, the above is right. Maybe your strings have literal backslash n rather than newline characters? Also in some langs you may need to add the m (multiline) modifier.
2

this is the pattern I would use

$string = preg_replace('@[\s]{2,}@',' ',$string);

1 Comment

There is no advantage in wrapping \s in braces in this pattern.
2

I often prefer \R to isolate newline sequences in regex patterns, but in this case, it is not necessary to keep potential \r-\n pairs coupled together -- they are all going to be consumed anyhow. Just use \v+ to match 1 or more consecutive vertical whitespace characters and replace them with a single space. You may also want to call trim() to clean up any leading or trailing spaces. (Demo)

$string = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

var_export(
    preg_replace('/\v+/', ' ', trim($string))
);

If anyone runs into corrupted multibyte characters, just add the u pattern modifier to set the regex engine in unicode mode (/\v+/u).

Comments

1

Using a combination of solutions mentioned above, this one line worked for me

 $string = trim(str_replace('\n', '', (str_replace('\r', '', $string))));

It removes '\r' and '\n'.

1 Comment

This is what actually worked for me!
0

This one also removes tabs

$string = preg_replace('~[\r\n\t]+~', '', $text);

Comments

0

You can try below code will preserve any white-space and new lines in your text.

$str = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

echo preg_replace( "/\r|\n/", "", $str );

Comments

0

this below code work all text please use it:

$des = str_replace('\n',' ',$des);
$des = str_replace('\r',' ',$des);

Comments

0

You can remove new line and multiple white spaces.

$pattern = '~[\r\n\s?]+~';
$name="test1 /
                     test1";
$name = preg_replace( $pattern, "$1 $2",$name);

echo $name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.