In the context of PHP forum discussions, how can developers optimize and simplify their code for word highlighting using preg_replace?
To optimize and simplify code for word highlighting using preg_replace in PHP forums, developers can use the following code snippet. By using preg_replace with a callback function, developers can easily highlight specific words in a string without the need for complex logic or multiple lines of code.
$text = "This is a sample text where we want to highlight specific words.";
$words_to_highlight = array("sample", "highlight");
$highlighted_text = preg_replace_callback(
'/\b(' . implode('|', $words_to_highlight) . ')\b/i',
function($match) {
return "<span style='background-color: yellow;'>{$match[0]}</span>";
},
$text
);
echo $highlighted_text;