![]() |
VOOZH | about |
Given a string element containing some spaces and the task is to remove all the spaces from the given string str in PHP. In order to do this task, we have the following methods in PHP:
Table of Content
The str_replace() method is used to replace all the occurrences of the search string (" ") by replacing string ("") in the given string str.
Syntax:
str_replace($searchVal, $replaceVal, $subjectVal, $count)
Example :
GeeksforGeeks
The str_ireplace() method is used to replace all the occurrences of the search string (" ") by replacing string ("") in the given string str. The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.
Syntax:
str_ireplace($searchVal, $replaceVal, $subjectVal, $count)
Example :
GeeksforGeeks
The preg_replace() method is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )
Example :
GeeksforGeeks
Using explode() and implode() to remove all white spaces in a string involves splitting the string into an array of words with explode(' ', $string), then rejoining the array elements into a single string without spaces using implode('', $array).
Example:
HelloWorld
Using `explode()` to split the string into an array at spaces and `implode()` to join array elements removes all spaces effectively. This approach transforms the string into a contiguous sequence of characters, useful for processing data where whitespace is irrelevant.
Example : PHP code splits the string "Hello World" into an array at spaces using `explode()`, then removes spaces by joining array elements with `implode()`, outputting "HelloWorld".
HelloWorld
Using filter_var() in PHP, you can remove all white spaces from a string. This function can sanitize the string by stripping high and low ASCII characters, effectively removing unwanted spaces.
Example:
Hello World!
The str_split() function splits the string into an array of single characters. The array_filter() function is then used to remove the spaces from this array. Finally, implode() is used to join the remaining characters back into a string without spaces.
Example:
GeeksforGeeks
In this approach we iterate through each character of a string and checks if it's not a white space (' ', "\t", "\n", "\r", "\0", "\x0B"), and concatenate non-white space characters to build a new string.
Example: In this example we removes whitespace characters from a string ($string) using a loop and conditionals.
GeeksForGeeks!