What is the purpose of using preg_replace in PHP to remove BB codes from text stored in a MySQL database?
The purpose of using preg_replace in PHP to remove BB codes from text stored in a MySQL database is to clean the text of any unwanted formatting before displaying it on a webpage. BB codes are often used to format text in forums or messaging systems, but they can interfere with the layout of a webpage if not properly handled.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Retrieve text from database
$query = "SELECT text FROM table";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$text = $row['text'];
// Remove BB codes using preg_replace
$clean_text = preg_replace('/\[[^\]]*\]/', '', $text);
// Display cleaned text
echo $clean_text;