mathewraj7786
mathewraj7786

Reputation: 273

Remove trailing newline

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?

Upvotes: 27

Views: 26541

Answers (2)

codaddict
codaddict

Reputation: 455052

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

Upvotes: 61

soulmerge
soulmerge

Reputation: 75704

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().

Upvotes: 13

Related Questions