By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Remove spaces from end of string with PHP

Tutorial on how to remove characters from the end of a string with PHP.

Edited: 2012-12-23 16:35

To remove certain characters from the end of a string using PHP, you would typically use the rtrim function, which will remove characters from the right end of the string.

Without the second parameter the rtrim function will only remove whitespace characters such as:

  1. " " (Space).
  2. "\t" (Tab).
  3. "\n" (New line.)
  4. "\r" (Carriage return.)
  5. "\0" (NUL-byte.)
  6. "\x0B" (Vertical tab.)

The below script will only remove whitespace from the end of a string, it is using the rtrim function.

 $text = "\t\tJust an example string :-)  \t";
 $rtrimmed = rtrim($text);
 echo $rtrimmed;

Removing other characters

To remove other characters than the default ones, you will have to use the second parameter of the rtrim function. An example of how to remove the "abc" letters from the end of the string is included below:

 $text = "abcdefg abc abc";
 $rtrimmed = rtrim($text, "abc");
 echo $rtrimmed;

Note. The string will be re-checked, meaning that both "abc" parts will be removed from the end.

More Tutorials

  1. Remove spaces from the beginning of a string
  2. Remove spaces from the beginning and end of a string