333
$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 ";
Marco Demaio
  • 32,321
  • 33
  • 125
  • 157
James
  • 38,737
  • 52
  • 130
  • 161
  • 1
    If you're doing thousands of replacements, avoid using `preg_replace`. It is almost twice as slow as `str_replace`. – Alex W Jun 20 '14 at 13:23
  • You might find [`s($str)->normalizeLineEndings('')`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L540) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). It will remove not only LF, CR and CRLF, but also any Unicode newline. – caw Jul 26 '16 at 23:58

21 Answers21

645

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));
jwueller
  • 29,756
  • 4
  • 63
  • 69
  • 11
    Before you use this solution, see my answer below and the comments to my answer. This solution may not work as you expect. – matsolof Sep 23 '10 at 08:30
  • 1
    in regular expression "\s Match a whitespace character", why would it match a newline? – Michael Z Jun 11 '14 at 00:00
  • 2
    I was searching for a solution to remove/replace all whitespaces but not (double) spaces. This is the regex that did it: `/(?![ ])\s+/` – algorhythm Jul 31 '15 at 07:53
  • 1
    Just wanted to let u know that Your solution has saved me a lot of time. – Parthapratim Neog Jul 31 '15 at 10:26
  • 2
    Wrong. \s matches any whitespace including space, tab, newline, carriage return. I have no idea how this got so many upvotes. To match newlines you need \r?\n which is a newline optionally preceded by a carriage return. – ekerner Oct 12 '20 at 01:13
194

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));
matsolof
  • 2,525
  • 3
  • 17
  • 17
100

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

NullUserException
  • 81,190
  • 27
  • 202
  • 228
23
$string = str_replace(array("\n", "\r"), ' ', $string);
fabrik
  • 13,717
  • 8
  • 55
  • 70
15

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);
Jimmix
  • 4,744
  • 2
  • 25
  • 56
Peter
  • 8,127
  • 6
  • 53
  • 92
15

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

str_replace(array("\r\n","\r"),"",$string);
RobertPitt
  • 55,891
  • 21
  • 113
  • 158
9

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

bobble bubble
  • 11,625
  • 2
  • 24
  • 38
Anton
  • 129
  • 1
  • 1
8

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);
Dave
  • 3,046
  • 7
  • 19
  • 32
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 ''.

n00dle
  • 5,782
  • 2
  • 33
  • 48
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);
NullUserException
  • 81,190
  • 27
  • 202
  • 228
netom
  • 3,242
  • 2
  • 20
  • 21
  • Please format your code properly. This is done by indenting the relevant line by four spaces. – jwueller Sep 21 '10 at 13:38
  • 2
    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. – NullUserException Sep 21 '10 at 13:42
5

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 ...

GDY
  • 2,695
  • 1
  • 22
  • 42
  • This doesn't seem to replace \r but just \n: https://www.ideone.com/28KPcb – T30 May 13 '19 at 11:40
  • 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. – GDY May 15 '19 at 07:29
  • 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. – GDY May 15 '19 at 07:34
4

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.

ekerner
  • 5,424
  • 1
  • 36
  • 31
  • 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. – Adam Whateverson Apr 08 '19 at 16:36
  • @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. – ekerner Oct 12 '20 at 01:17
2

this is the pattern I would use

$string = preg_replace('@[\s]{2,}@',' ',$string);
Rajeev
  • 4,181
  • 2
  • 21
  • 35
2

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

This one also removes tabs

$string = preg_replace('~[\r\n\t]+~', '', $text);
user3213174
  • 65
  • 2
  • 9
1

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 );
PCMShaper
  • 31
  • 4
1

maybe this works:

$str='\n';
echo str_replace('\n','',$str);
زياد
  • 862
  • 10
  • 14
1

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;
Ramesh
  • 1,321
  • 11
  • 14
1

Very simple

$hello = "
A
B
C
";
str_replace("
", " ", $hello);
// A B C
Minco
  • 21
  • 1
0

this below code work all text please use it:

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

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'.

Kashif
  • 1