Home » Php » Remove newline character from a string using php regex

Remove newline character from a string using php regex

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

How to&Answers:
$string = str_replace("\n", "", $string);
$string = str_replace("\r", "", $string);

Answer:

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

or

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

Answer:

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

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

Answer:

Better to use,

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

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

Answer:

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

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

Answer:

Try this out
Its working for me

First remove n from string (use double slash before n),

Then remove r from string like n

CODE :

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

Answer:

Use strtr

Here’s the fastest way to get rid of newlines:

    // method 1
    $s = strtr($s,"\n\r","  ");

This will only replace newlines with spaces. Actually, this is desirable when you process html texts; it doesn’t join words at the ends of lines (e.g. “bro” at the end and “Ken” in next line won’t become “broKen”). Meanwhile, it’s very-very fast, doesn’t change the length of the string (spares a lot of data moving!), and doesn’t need anything else but character-level processing which is insanely efficient. (As opposed to giving arrays to strtr which is noticeably slower)

Now if, for some reason, you want to actually remove newlines:

    // method 2
    $s = strtr($s,["\n"=>"","\r"=>""]);  

    // method 3
    $s = preg_replace('/[\r\n]/','',$s);  

These methods run almost at the same speed with reasonably short plain text strings. But with a heavier payload (a 4MB text), subtle differences start to show:

Long strings

4MB text with 70 thousand line breaks:
 - method 1: 3.26ms  // strtr("")
 - method 2: 8.58ms  // strtr([]) is slower
 - method 3: 6.05ms  // preg beats strtr! never expected that!

4MB text with 1.3 million line breaks:
 - method 1: 3.26ms  // stays the same, no matter how many replaces!
 - method 2: 33.12ms  // more work to do, slower execution
 - method 3: 55.73ms  // preg performs worst this time

Method 1 is the absolute winner. It doesn’t care how many characters it has to replace – it touches everything once and only once.

Method 2 and 3: when there’s a lot to replace, strtr with arrays is much more efficient than preg. In the case of a normal text (with 80-100 characters per line) preg beats strtr by a little; still, I would typically go for strtr in this case too. But yes, preg is surprisingly fast, especially compared to what it’s capable of.

TLDR:

  • if the output of method 1 is good enough, always go with that;
  • otherwise, the expected number of line breaks should decide the match;
  • always be yourself unless you can be Batman.

A note on PHP_EOL: I’ve seen answers mentioning this constant, suggesting that we should only replace the “official” end-of-line sequence, like CRLF for windows. Now this is usually a mistake: while it seems super-appropriate, it will handle files wrong if they weren’t created on the same platform. You’re running on Linux, you process a file uploaded from Windows – alas, you’re full of “\r”. So don’t. It’s for same-platform operations only.

Answer:

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.

Answer:

     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