The PHP trim function is used to remove whitespace and other characters from the beginning and end of a string. Not all data (especially data from external sources) comes clean and nicely formatted. Sometimes we get additional characters which have found their way onto our data.
In this PHP trim string tutorial, we will be looking at how to remove these unnecessary and unwanted characters in an effort to clean up our data before we process it using our script.
The characters that are treated as whitespace by the PHP trim string function are:
Character | Description |
---|---|
" " | Space |
"\t" | Tab |
"\n" | New Line |
"\r" | Carriage Return |
"\0" | Null Byte |
"\x0B" | Vertical Tab |
That is, when the PHP trim function is used to process a string, the PHP interpreter will remove the above characters from the beginning and end of that string if they are present.
The syntax for the simplest form of the trim function in PHP is given below:
$result = trim($string);
Where $string is the string that you want to be trimmed and $result is the variable that holds the result after the function is performed.
Take a look at the example below which shows the PHP trim string function at work:
<?php // build a string with some whitespace $text = "\n\t This is a simple string :-) ...! \t\n"; // dump the string so we can see the size of it var_dump($text); echo '<br />'; // trim the string $result = trim($text); // dump the string again so we can see the size of it var_dump($result); ?>
When we run this code we get:
At first, we see that the string was 41 characters long, and then we see that PHP managed to trim 9 whitespace characters from the beginning and end of the string to make the new string 32 characters long. We stripped a newline, a tab, and a space from the beginning of the string; 4 spaces, a tab, and a newline from the end of the string, for a total of 9 characters.
Notice that whitespace inside the string (such as the spaces between words) is not affected by the PHP trim function. Remember, the PHP trim string function only operates on whitespace characters at the beginning and end of a string.