coderex
coderex

Reputation: 27845

Remove newline character from a string using PHP regex

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

Upvotes: 57

Views: 84356

Answers (10)

Mukesh Chapagain
Mukesh Chapagain

Reputation: 25948

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

Upvotes: 1

dkellner
dkellner

Reputation: 9906

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.

Upvotes: 2

Atul Baldaniya
Atul Baldaniya

Reputation: 879

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

Upvotes: -1

Muhammed Suhail
Muhammed Suhail

Reputation: 289

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

Upvotes: 2

timmz
timmz

Reputation: 2252

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

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

Upvotes: 20

Robert Sinclair
Robert Sinclair

Reputation: 5406

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.

Upvotes: 5

tfont
tfont

Reputation: 11233

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

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

Upvotes: 5

AntonioCS
AntonioCS

Reputation: 8496

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

or

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

Upvotes: 103

Bhavesh G
Bhavesh G

Reputation: 3028

Better to use,

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

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

Upvotes: 8

Harmen
Harmen

Reputation: 22438

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

Upvotes: 53

Related Questions