trim()
Remove characters from the front and back of a string. By default it will remove whitespace (space, tab, new line, cariage return, nul-byte, and verticle tab) but you can optionally pass in a list of characters (as a string) you want to have it remove.
Some things to remmeber:
- Doesn’t change the original string - be sure to save or print the return value
- Your list of characters overwrites the defaluts - the optional list of characters you pass in is not in addition to the default values
- Your list of characters must be a string - it’s not an array, just a bunch of characters next to each other in a string
- Only acts on the outsides of the string - once it finds a character not in the list, it stops on that side of the string
$str = " Hi mom. I'm in jail!\n\n"; $res = trim($str); echo '*' . $res . '*'; // *Hi mom. I'm in jail!* $chars = "\n! m"; // that new line character (\n) needs to be in double quotes $res = trim($str, $chars); echo '*' . $res . '*'; // *Hi mom. I'm in jail* $chars = "a..lH\n!"; // specify a range with .. between two characters $res = trim($str, $chars); echo '*' . $res . '*'; // * Hi mom. I'm in *
In the last example, we specified a range of characters with a “double dot” a..l which means a through l inclusive. This, along with the other characters in our list, resulted in the removal of the last word completely.
