In this tutorial, we'll look into how you can remove whitespace and other characters from a string using the
trim() function in PHP.
I find this method particularly useful in cases where an application accepts user input to store in a database. The
trim() function removes any whitespace surrounding a string's value, resulting in a correctly stored value in the database table.
What is the PHP
trim() function in PHP removes whitespace and any other specified characters from both the left and right sides of a string.
Alternatively, you can use the
ltrim() function to remove whitespace from only the left side of a string and
rtrim() to remove whitespace from only the right side of a string.
Syntax & Parameters
The syntax for the PHP
trim() function looks like this:
Here is a breakdown of each of the parameters:
$string: A required, hard-coded string or variable containing the text you want to remove whitespaces or characters.
$chars: An optional parameter where you can pass in specific characters to remove. If this parameter is left empty, the function will remove whitespace from both sides of a string by default.
Character Removal Examples
Here are a few examples you can use when passing in a value for the $chars parameter:
"\r"- Carriage return
"\t"- Horizontal tab
"\x0B"- Vertical tab
" "- Whitespace
To remove whitespace from both sides of a string, use the following example:
$string = " This is a string ";
The output for the above example will show as follows:
This is a string
You can specify certain characters to remove from a string, as well:
$string = "This is a string";
echo trim($string, "ing");
Resulting in the following output:
This is a str
As you can see, the text "ing" is now omitted from our resulting string, showing a partially removed sentence.
trim() function provides simple functionality that packs a punch when you need something quick and useful to clean up your data. Alternatively, the
rtrim() functions can be used for trimming specific sides of your strings.