What is the best method to highlight words when retrieving them from a database in PHP?
When retrieving words from a database in PHP and you want to highlight specific words within the retrieved text, one common method is to use the `str_replace()` function to replace the words with HTML tags for highlighting. You can wrap the words with `<span>` tags and apply a CSS class for styling. This allows you to visually emphasize the words when displaying them on a webpage.
<?php
// Retrieve text from the database
$text = "This is a sample text with some words to highlight.";
// Words to highlight
$wordsToHighlight = array("sample", "words");
// Loop through each word to highlight
foreach($wordsToHighlight as $word) {
$text = str_replace($word, "<span class='highlight'>$word</span>", $text);
}
// Display the highlighted text
echo $text;
?>