How can str_replace() be used to highlight words in PHP and what precautions should be taken before implementation?
To highlight words in PHP using str_replace(), you can replace the target words with HTML tags for highlighting, such as <span style="background-color: yellow">word</span>. However, before implementing this, you should ensure that the input is sanitized to prevent XSS attacks by using functions like htmlspecialchars() or htmlentities().
<?php
$input_text = "This is a sample text with some words to highlight.";
$words_to_highlight = ["sample", "words"];
foreach ($words_to_highlight as $word) {
$input_text = str_replace($word, '<span style="background-color: yellow">' . $word . '</span>', $input_text);
}
echo $input_text;
?>
Related Questions
- What are best practices for handling user input validation before storing in session variables in PHP?
- What are the risks involved in manually replacing PHP versions in a server setup, and how can data loss be prevented during the process?
- Are there any best practices to follow when integrating JavaScript with PHP for user interactions?