How can PHP functions like preg_replace and htmlspecialchars be utilized to maintain formatting integrity when working with text data retrieved from a database?
When working with text data retrieved from a database, it is important to maintain formatting integrity to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. PHP functions like preg_replace and htmlspecialchars can be utilized to sanitize the data before displaying it to the user. preg_replace can be used to remove any potentially harmful characters or scripts, while htmlspecialchars can be used to convert special characters to HTML entities to prevent them from being interpreted as code.
// Retrieve text data from the database
$text = $row['text'];
// Sanitize the text data using preg_replace and htmlspecialchars
$sanitized_text = htmlspecialchars(preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $text));
// Display the sanitized text
echo $sanitized_text;