views:

44

answers:

2

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 :( Please help

Thanks everyone.

+4  A: 

You need to add the end of line anchor:

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

Its better to avoid regex for such a simple substitution. This can easily be done using rtrim as:

$string = rtrim($string);

rtrim without 2nd argument will remove the trailing whitespace char which include:

  • newline
  • space
  • vertical tab
  • horizontal tab
  • carriage return
codaddict
+2  A: 

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

soulmerge
+1 for getting the value trimmed from the db
Gordon