Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing newline

Tags:

I've a MySQL database from which I extract a string which is a list of words separated by newline. Now I want to remove only the trailing newline.

I tried using preg_replace as

$string = preg_replace('/\n/','',$string); 

It works, but all the newlines in the strings are removed :(

How can I do this?

like image 276
mathewraj7786 Avatar asked Aug 20 '10 10:08

mathewraj7786


People also ask

How do you remove the trailing newline in Python?

Use the strip() Function to Remove a Newline Character From the String in Python. The strip() function is used to remove both trailing and leading newlines from the string that it is being operated on. It also removes the whitespaces on both sides of the string.

Does Strip remove newline?

Using strip() method to remove the newline character from a string. The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.

What is a trailing newline?

When a line break occurs at the end of a block of text, it is called a trailing newline. The newline character is important in computer programming, since it allows programmers to search for line breaks in text files.


2 Answers

You need to add the end of line anchor:

$string = preg_replace('/\n$/','',$string); 

It's better to avoid regular expressions for such a simple substitution. This can easily be done using rtrim as:

$string = rtrim($string); 

rtrim without the second argument will remove the trailing whitespace characters which include:

  • newline
  • space
  • vertical tab
  • horizontal tab
  • carriage return
like image 112
codaddict Avatar answered Oct 21 '22 21:10

codaddict


Don't use regular expressions for such a trivial task. You can use PHP's rtrim() (possibly with "\n" as the second parameter) or substr() (like substr($string, 0, -1)) or MySQL's RTRIM().

like image 22
soulmerge Avatar answered Oct 21 '22 21:10

soulmerge