57

How can I remove a new line character from a string using PHP?

10 Answers 10

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

or

$string = str_replace(array("\n","\r"), '', $string);
Sign up to request clarification or add additional context in comments.

3 Comments

Not working for me. First, that PHP_EOL was not recognized at all. Second, if you first remove \n and then you are searching for \r\n you won't find them, because \n is removed already.
@MilanG You can look here for all the predefined php constants: php.net/manual/en/reserved.constants.php You will see there PHP_EOL. You are probably correct regarding your second statement, I will fix this. Thanks
I'm trying to remove \n from a word, I'm not able to do with above code \nStretcher
53
$string = str_replace("\n", "", $string);
$string = str_replace("\r", "", $string);

Comments

20

To remove several new lines it's recommended to use a regular expression:

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

3 Comments

the + symbol means 1 or more, you don't need the first \s.
Doesn't the \s regex group include things like tabs, and common spaces, in which case this answer is grossly-over-greedy?
Why is it recommended?
8

Better to use,

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

Because some line breaks remains as it is from textarea input.

Comments

5

Something a bit more functional (easy to use anywhere):

function strip_carriage_returns($string)
{
    return str_replace(array("\n\r", "\n", "\r"), '', $string);
}

Comments

5

stripcslashes should suffice (removes \r\n etc.)

$str = stripcslashes($str);

Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation.

1 Comment

Why did it take more than nine years?
2

Try this out. It's working for me.

First remove n from the string (use double slash before n).

Then remove r from string like n

Code:

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

1 Comment

Why is it simpler than Harmen's answer?
2

Let's see a performance test!

Things have changed since I last answered this question, so here's a little test I created. I compared the four most promising methods, preg_replace vs. strtr vs. str_replace, and strtr goes twice because it has a single character and an array-to-array mode.

You can run the test here:

        https://deneskellner.com/stackoverflow-examples/1991198/

Results

     251.84 ticks using  preg_replace("/[\r\n]+/"," ",$text);
      81.04 ticks using  strtr($text,["\r"=>"","\n"=>""]);
      11.65 ticks using  str_replace($text,["\r","\n"],["",""])
       4.65 ticks using  strtr($text,"\r\n","  ")

(Note that it's a realtime test and server loads may change, so you'll probably get different figures.)

The preg_replace solution is noticeably slower, but that's okay. They do a different job and PHP has no prepared regex, so it's parsing the expression every single time. It's simply not fair to expect them to win.

On the other hand, in line 2-3, str_replace and strtr are doing almost the same job and they perform quite differently. They deal with arrays, and they do exactly what we told them - remove the newlines, replacing them with nothing.

The last one is a dirty trick: it replaces characters with characters, that is, newlines with spaces. It's even faster, and it makes sense because when you get rid of line breaks, you probably don't want to concatenate the word at the end of one line with the first word of the next. So it's not exactly what the OP described, but it's clearly the fastest. With long strings and many replacements, the difference will grow because character substitutions are linear by nature.

Verdict: str_replace wins in general

And if you can afford to have spaces instead of [\r\n], use strtr with characters. It works twice as fast in the average case and probably a lot faster when there are many short lines.

Comments

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

\R matches a generic newline; that is, anything considered a linebreak sequence by Unicode.

https://perldoc.perl.org/perlrebackslash#Misc

\R can be used instead of \r\n.

Comments

-1

Use:

function removeP($text) {
    $key = 0;
    $newText = "";
    while ($key < strlen($text)) {
        if(ord($text[$key]) == 9 or
           ord($text[$key]) == 10) {
            //$newText .= '<br>'; // Uncomment this if you want <br> to replace that spacial characters;
        }
        else {
            $newText .= $text[$key];
        }
        // echo $k . "'" . $t[$k] . "'=" . ord($t[$k]) . "<br>";
        $key++;
    }
    return $newText;
}

$myvar = removeP("your string");

Note: Here I am not using PHP regex, but still you can remove the newline character.

This will remove all newline characters which are not removed from by preg_replace, str_replace or trim functions

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.