PHP's trim() function
Posted June 11th, 2009 in PHP
PHP's trim() function has a second parameter which allows a list of characters to trim to be passed in. This allows characters other than (or instead of) the default space character to be trimmed from a string. It works for trim(), rtrim() and ltrim().
The way trim() works is to remove whitespace from the start and end of the string passed in; rtrim() only does it to the end of the string (r = right) and ltrim() to the start of the string (l = left).
If you wanted to also trim off e.g. hypens and underscores then this can be passed in the character list as the second parameter like so:
$trimmed = trim($source, " -_"); $left_trimmed = ltrim($source, " -_"); $right_trimmed = rtrim($source, " -_");
In the above example, if $source was "_abc- " then $trimmed would be "abc".
I know this is pretty simple stuff, but often even when you've been programming in a particular language for several years you still may not be aware of all the parameters that can be passed to functions that can be real time savers.

Comments
blog comments powered by Disqus