What are best practices for effectively removing spaces, line breaks, and   from strings in PHP?

When working with strings in PHP, it is common to encounter unwanted spaces, line breaks, and non-breaking spaces ( ). To effectively remove these from a string, you can use PHP's built-in functions like trim(), preg_replace(), and str_replace().

// Remove spaces and line breaks
$string = "   Hello\nWorld   ";
$clean_string = preg_replace('/\s+/', ' ', $string);

// Remove  
$clean_string = str_replace(' ', '', $clean_string);

echo $clean_string;