Home > Backend Development > PHP Tutorial > How to Remove Spaces (or All Whitespace) from a String in PHP?

How to Remove Spaces (or All Whitespace) from a String in PHP?

Linda Hamilton
Release: 2024-12-12 13:56:14
Original
979 people have browsed it

How to Remove Spaces (or All Whitespace) from a String in PHP?

How to Remove All Spaces from a String in PHP

In PHP, you can remove all spaces from a string using either the str_replace() function or the preg_replace() function.

Using str_replace()

If you only want to remove spaces, you can use the str_replace() function. The following code snippet demonstrates how to use it:

$string = "this is my string";
$string = str_replace(' ', '', $string);
echo $string; // Output: thisismystring
Copy after login

Using preg_replace()

If you want to remove all whitespace characters, including spaces, tabs, and line endings, you can use the preg_replace() function. The following code snippet demonstrates how to use it:

$string = "this is my string";
$string = preg_replace('/\s+/', '', $string);
echo $string; // Output: thisismystring
Copy after login

The /s regular expression pattern matches one or more whitespace characters. The '' replacement string specifies that matched whitespace characters should be removed.

The above is the detailed content of How to Remove Spaces (or All Whitespace) from a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template