You’ll want to process and tidy your user input before you do anything with it when building PHP apps.
trim() is one of the tools available to do this – it removes all white space from the beginning and end of a string.
Whitespace is things like spaces, tabs, and newlines which may be invisible to the user.
PHP trim Syntax
trim ( $string [, $character_mask = " \t\n\r\0\x0B" ] )
- By default, $string will be returned by trim() with all whitespace removed from the beginning and end, including:
- ” “, an ordinary space
- “\t”, a tab
- “\n”, a new line
- “\r”, a carriage return
- “\0”, the NUL-byte
- “\x0B”, a vertical tab
- If a second parameter, character_mask is passed, only the characters specified will be removed
$sentence = " \n \t This is a very poorly formatted sentence. \r "; $trimmed = trim($sentence); // "This is a very poorly formatted sentence." // Using a character mask, only spaces are trimmed $only_trim_spaces = trim($sentence, " "); // "\n \t This is a very poorly formatted sentence. \r"
Tip – if you want to output a string and see where the invisible characters are, you can echo the results of the json_encode() function
Users are unpredictable, and they love accidentally leaning on the spacebar when they’re done entering text into a form. trim() is a good way to tidy up user input before you store it in a database.
For the official documentation on the PHP trim() function, visit the link below: