PHP remove trailing whitespaces and newline

PHP has inbuilt function rtrim to remove specific or all trailing whitespaces from end of php string. preg_replace can also be used for this purpose. But using rtrim is more elegant. Here are few examples.

Remove all trailing whitespaces

By default rtrim will remove all trailing whitespaces (including space, tab, newline, etc.)

<?php
$old = "Abc \n\n   \n";
$new = rtrim($old);
echo "==old==\n";
var_dump($old);
echo "==new==\n";
var_dump($new);
?>
Env: PHP 5.5.9 (Linux)

Remove only trailing newline

One can specify only trailing carriage return and newline to be removed as optiona param to rtrim.

<?php
$old = "Abc \n\n\r\n";
$new = rtrim($old, "\r\n");
echo "==old==\n";
var_dump($old);
echo "==new==\n";
var_dump($new);
?>
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments