To replace multiple spaces with a single space in PHP, you can use the preg_replace()
function with a regular expression pattern.
The regular expression pattern is /\s+/\
, which matches one or more whitespace characters.
Here is an example:
$string = "Hello World!";
$newString = preg_replace('/\s+/', ' ', $string);
echo $newString;
In this example, the variable $string
contains the string "Hello World!"
with multiple spaces between the words.
The preg_replace()
function replaces all occurrences of one or more consecutive whitespace characters with a single space.
The resulting string, stored in the variable $newString
, will be "Hello World!"
.
Finally, the echo
statement outputs the modified string.