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?
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.
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.
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.
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:
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With