57

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
coderex
  • 27,225
  • 45
  • 116
  • 170

10 Answers10

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

or

$string = str_replace(array("\n","\r"), '', $string);
AntonioCS
  • 8,335
  • 18
  • 63
  • 92
  • 6
    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 Apr 08 '15 at 14:21
  • @MilanG You can look here for all the predefined php constants: http://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 – AntonioCS Apr 09 '15 at 15:35
  • I'm trying to remove \n from a word, I'm not able to do with above code ```\nStretcher``` – Kunal Rajput Apr 05 '22 at 08:15
53
$string = str_replace("\n", "", $string);
$string = str_replace("\r", "", $string);
Harmen
  • 22,092
  • 4
  • 54
  • 76
20

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

$my_string = trim(preg_replace('/\s\s+/', ' ', $my_string));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
timmz
  • 2,194
  • 3
  • 23
  • 29
8

Better to use,

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

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

Bhavesh G
  • 3,000
  • 4
  • 39
  • 66
5

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

function strip_carriage_returns($string)
{
    return str_replace(array("\n\r", "\n", "\r"), '', $string);
}
tfont
  • 10,891
  • 7
  • 56
  • 52
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.

Robert Sinclair
  • 4,550
  • 2
  • 44
  • 46
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Muhammed Suhail
  • 269
  • 2
  • 6
  • Why is it simpler than [Harmen's answer](https://stackoverflow.com/questions/1991198/remove-newline-character-from-a-string-using-php-regex/1991211#1991211)? – Peter Mortensen Jul 16 '20 at 20:55
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dkellner
  • 8,726
  • 2
  • 49
  • 47
0
$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.

Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120
-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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Atul Baldaniya
  • 761
  • 8
  • 14