trim
Remove spaces (or other characters) from the beginning and end of the string
The trim()
function removes whitespace characters or other predefined characters on both sides of the string.
ltrim()
- Removes whitespace or other predefined characters to the left of the stringrtrim()
- Removes whitespace or other predefined characters to the right of the stringRemove characters on both sides of the string ("He" in "Hello" and "d!" in "World"):
<?php $str = "Hello World!" ; echo $str . "<br>" ; echo trim ( $str , "Hed!" ) ; ?>
Try it yourself
Remove spaces on both sides of the string:
<?php $str = " Hello World!" ; echo "Don't use trim: " . $str ; echo "<br>" ; echo "Use trim: " . trim ( $str ) ; ?>
The HTML output of the above code is as follows (please check the source code):
< ! DOCTYPE html > < html > < body > Don't use trim : Hello World ! < br > Use trim : Hello World ! < / body > < / html >
The browser output of the above code is as follows:
Don't use trim: Hello World! Use trim: Hello World!
Try it yourself
Remove the newline character (\n) on both sides of the string:
<?php $str = "\n\n\n\nHello World!\n\n\n" ; echo "Don't use trim: " . $str ; echo "<br>" ; echo "Use trim: " . trim ( $str ) ; ?>
The HTML output of the above code is as follows (please check the source code):
< ! DOCTYPE html > < html > < body > Don't use trim : Hello World ! < br > Use trim : Hello World ! < / body > < / html >
The browser output of the above code is as follows:
Don't use trim: Hello World! Use trim: Hello World!
Try it yourself
trim ( string , charlist )
parameter | describe |
---|---|
string | Required. Specifies the string to be checked. |
charlist |
Optional. Specifies which characters to delete from the string. If omitted, all the following characters are removed:
|