How can preg_match and preg_replace be used to format text from a database for output in PHP?

When retrieving text from a database for output in PHP, it may contain unwanted formatting such as HTML tags or special characters. To clean up the text, you can use preg_match and preg_replace functions to remove or replace these unwanted elements. Preg_match can be used to match specific patterns in the text, while preg_replace can be used to replace those patterns with desired content.

// Retrieve text from database
$text = "<p>This is some <b>sample</b> text with <a href='#'>HTML tags</a>.</p>";

// Remove HTML tags from text
$clean_text = preg_replace("/<[^>]*>/", "", $text);

// Output cleaned text
echo $clean_text;