[php] Remove new lines from string and replace with one empty space

$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 ";

This question is related to php regex string

The answer is


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


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


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);

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 );

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

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

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


this below code work all text please use it:

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

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;

maybe this works:

$str='\n';
echo str_replace('\n','',$str);

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.


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


This one also removes tabs

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

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

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


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);

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));

this is the pattern I would use

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

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);

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript