What are the best practices for replacing multiple consecutive spaces with " " in PHP?

When dealing with multiple consecutive spaces in PHP, it is common to replace them with the non-breaking space character " " to ensure they are displayed correctly in HTML. One way to achieve this is by using the preg_replace function with a regular expression pattern that matches multiple spaces. This will allow you to easily replace all instances of consecutive spaces with " " in a given string.

// Input string with multiple consecutive spaces
$inputString = "Hello    world";

// Replace multiple consecutive spaces with " "
$outputString = preg_replace('/\s+/', ' ', $inputString);

// Output the modified string
echo $outputString;