PHP Basics

PHP Remove Extra Spaces Whitespace from end of string

In PHP Projects, may need to remove extra spaces whitespace from end of string. There is a string that ends with a single white space or multiple extra spaces. Then we can use PHP trim function to remove the white space at the end of the string.

PHP trim() Function

This function not only removes white space at the end of the string but also at the beginning of the string.

<?php

echo $username;

$username=trim($username);

echo $username;

?>

Output:

“Srikant        ”

“Srikant”

PHP rtrim() Function

Alternatively, we can use rtrim function to remove white spaces at the end of the string.

<?php

echo $username;

$username=rtrim($username);

echo $username;

?>

Output:

“Srikant        ”

“Srikant”

Remember

In PHP, rtrim function removes extra spaces whitespace from the end of the string while trim function removes extra space white space from both beginning and end of the string.