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); ?>
==old== string(10) "Abc " ==new== string(3) "Abc"
Env: PHP 7.4.33 (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); ?>
==old== string(8) "Abc " ==new== string(4) "Abc "
Env: PHP 7.4.33 (Linux)