How can we remove the white spaces from string in PHP?

It depends on which spaces you want to remove.

NeedFunction
Remove spaces from both endstrim()
Remove spaces from the left side onlyltrim()
Remove spaces from the right side onlyrtrim()
Remove all spaces everywherestr_replace(" ", "", $text)
Remove spaces, tabs and new lines everywherepreg_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
Exercises & Assignments
Write a PHP program to reverse the string
Write a PHP program to find the length of the string
Write a PHP program to count the words in the string
Write a PHP program to convert a string into uppercase
Interview Questions & Answers
How will you concatenate two strings in PHP?
What is the difference between single quote and double quote string in PHP?
Why we use PHP String functions trim(), ltrim() and rtrim()?
What PHP Function is used to find position of a string?
What is the use of ucwords() PHP String function?
What is the use of str_replace() PHP String function?
How to find String Length in PHP?