Home >Backend Development >PHP Problem >What are the ways to remove spaces in strings in php
There are two ways to remove spaces in strings in php: 1. Define the variable $str to save the string to be changed. Use the "str_replace()" function to replace all spaces with an empty string. Space, the syntax is "str_replace(' ', '', $str); 2. The "preg_replace()" function uses regular matching, the syntax is "preg_replace('/\s /', '', $str)".
The operating system of this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
How to remove spaces in strings in php There are two types:
1. Use str_replace()
$str = "This is a string with spaces."; $new_str = str_replace(' ', '', $str); echo $new_str; // Thisisastringwithspaces.
In the above code, a string $str containing spaces is first defined. Then we use The str_replace() function replaces all spaces with an empty string '' and stores the result in a new variable $new_str. Finally, we output the value of $new_str, which should be a version of the original string with all spaces removed .
2. Use preg_replace()
$str = "This is a string with spaces."; $new_str = preg_replace('/\s+/', '', $str); echo $new_str; // Thisisastringwithspaces.
In this example, use the similar function preg_replace() to replace all spaces. The difference from the previous one is, It uses the regular expression /\s / to match any whitespace character and replace it with an empty string. Syntax /\s / uses slashes to identify the beginning and end of the regular expression, \s matches any whitespace character, matches one or more matched characters.
The above is the detailed content of What are the ways to remove spaces in strings in php. For more information, please follow other related articles on the PHP Chinese website!