- Instant help with your Php coding problems

Remove whitespace from the beginning and end of a string in PHP

Question:
How to remove whitespace from the beginning and end of a string in PHP?
Answer:
$text = "  sample text \r\n";

echo trim($text); // 'sample text'
Description:

When handling user input, it may be necessary to clean the input data. Part of this process involves removing invisible characters from the beginning and end of the text, which may be accidental or intentional. For example, a user may type only a few space characters in place of a required field.
In PHP, you can do this cleanup using the trim function, like this:

trim(' username\r\n'); // 'username'


By default, the trim function removes all normal space   characters from the beginning and end of the text. Besides this, it also removes the following whitespace characters:

  • "\t" - tab.
  • "\n" - new line
  • "\r" - carriage return
  • "\0" - the NUL-byte.
  • "\v" - vertical tab.

It's good to know that you can specify a list of characters as the second parameter of the trim function, and the function will remove these characters as well.

For example:

echo trim('apple','ae'); // ppl
Reference:
PHP trim reference
Share "How to remove whitespace from the beginning and end of a string in PHP?"
Interesting things
ChatGPT in a nutshell