What are best practices for removing extra spaces or line breaks when displaying textarea content in PHP?

When displaying textarea content in PHP, it's common to encounter extra spaces or line breaks that can affect the formatting of the text. To remove these unwanted characters, you can use the PHP functions trim() to remove leading and trailing spaces, and preg_replace() with a regular expression to remove extra line breaks.

// Sample textarea content
$textareaContent = "   This is some text with extra spaces and line breaks.   

    There are multiple line breaks here.

   ";

// Remove extra spaces and line breaks
$cleanedContent = preg_replace('/\s+/', ' ', trim($textareaContent));

// Display the cleaned content
echo $cleanedContent;