W3docs

Remove excess whitespace from within a string

To remove excess whitespace from within a string in PHP, you can use the preg_replace() function with a regular expression that matches any sequence of one or more whitespace characters.

To remove excess whitespace from within a string in PHP, you can use the preg_replace() function with a regular expression that matches any sequence of one or more whitespace characters.

Here is an example of how to use preg_replace() to remove excess whitespace from a string:

How to remove excess whitespace from within a string in PHP?

php— editable, runs on the server

The output of this code would be:


"This is a string with excess whitespace."

Alternatively, you can use the trim() function to remove leading and trailing whitespace from a string, and then use str_replace() to replace any remaining sequences of multiple whitespace characters with a single space. Here is an example of how to do this:

Example of using trim() function to remove leading and trailing whitespace from a string in PHP

php— editable, runs on the server

Both of these approaches will remove excess whitespace from within a string, leaving just a single space character between words.