Why we use PHP String functions trim(), ltrim() and rtrim()?
These functions remove white spaces (or other characters that you give) from the ends of a string. They are useful to clean the input of a form.
| Function | Removes from |
|---|---|
| trim() | Both sides |
| ltrim() | Left side (start) |
| rtrim() | Right side (end) |
<?php
echo "[" . trim(" Welcome ") . "]<br>";
echo trim("--Hello--", "-") . "<br>";
echo ltrim("007", "0") . "<br>";
echo rtrim("Hello!!!", "!");
?>
Output:
Tutorials Class - Output Window
[Welcome]
Hello
7
Hello
The second parameter is a list of characters to remove. If you skip it, PHP removes spaces, tabs, new lines and a few more invisible characters. These functions do not remove spaces from the middle of a string, see how to remove all white spaces.
Learn more about the similar topics:
| Tutorials |
|---|
| PHP String Handling |
| PHP explode() Function |
| PHP strpos() Function |
| PHP implode() Function |