Home » Programming » PHP » Php Trim

PHP trim() Function [With Examples]

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" ] )

Note that:

  • 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

Examples

$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

echo json_encode($trimmed);

Conclusion

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 more PHP tutorials, check out the PHP category on LinuxScrew

For the official documentation on the PHP trim() function, visit the link below:

https://www.php.net/manual/en/function.trim.php

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment