Remove whitespace from the beginning and end of a string in PHP
$text = " sample text \r\n";
echo trim($text); // 'sample text'
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
- Remove whitespace from the beginning and end of a string in PHP
- Locate a substring within a string in PHP
- Process CSV line in PHP
- Extract a substring from a string in PHP
- Split a string into words in PHP
- Replace spaces with dashes in PHP
- Replace only the first occurrence of a string in PHP
- Replace last occurrence of a string in a string in PHP
- Remove all attributes from HTML tags in PHP
- Remove HTML tags from a string except p, b, i and br in PHP
- Remove HTML tags from a string in PHP