How can we remove the white spaces from string in PHP?
It depends on which spaces you want to remove.
| Need | Function |
|---|---|
| Remove spaces from both ends | trim() |
| Remove spaces from the left side only | ltrim() |
| Remove spaces from the right side only | rtrim() |
| Remove all spaces everywhere | str_replace(" ", "", $text) |
| Remove spaces, tabs and new lines everywhere | preg_replace("/\s+/", "", $text) |
<?php
echo "[" . trim(" Hello PHP ") . "]<br>";
echo str_replace(" ", "", "a b c") . "<br>";
echo preg_replace('/\s+/', '', " a \n b\tc ");
?>
Output:
Tutorials Class - Output Window
[Hello PHP]
abc
abc
The trim functions can also remove other characters, see why we use trim(), ltrim() and rtrim().
Learn more about the similar topics:
| Tutorials |
|---|
| PHP String Handling |
| PHP explode() Function |
| PHP strpos() Function |
| PHP implode() Function |