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.

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

<?php

$string = "This   is   a  string   with   excess   whitespace.";
$string = preg_replace('/\s+/', ' ', $string);
echo $string;

The output of this code would be:

"This is a string with excess whitespace."

Watch a course Learn object oriented PHP

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:

<?php

$string = "   This   is   a  string   with   excess   whitespace.   ";
$string = trim($string); // Remove leading and trailing whitespace
$string = str_replace('  ', ' ', $string); // Replace sequences of 2 spaces with 1 space
while (strpos($string, '  ') !== false) {
  $string = str_replace('  ', ' ', $string); // Replace remaining sequences of 2 or more spaces with 1 space
}
echo $string; // Output: "This is a string with excess whitespace."

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