What are some best practices for efficiently removing spaces before punctuation marks in PHP?

When working with text in PHP, it is common to have spaces before punctuation marks that need to be removed for formatting consistency. One efficient way to achieve this is by using regular expressions to find and replace all spaces before punctuation marks. By using the preg_replace function with a regular expression pattern, we can easily remove these unnecessary spaces in a single line of code.

$text = "Hello , world ! This is a test .";
$cleaned_text = preg_replace('/\s+([.,!?])/', '$1', $text);
echo $cleaned_text;