What are the potential pitfalls of using str_replace, str_ireplace, and preg_replace in PHP for highlighting search terms in database output?
When using str_replace, str_ireplace, and preg_replace to highlight search terms in database output, a potential pitfall is that it may not handle HTML entities properly, leading to broken markup or security vulnerabilities like XSS attacks. To solve this issue, it is recommended to use htmlspecialchars or htmlentities to escape the search terms before using them in the replacement function.
// Example code snippet to safely highlight search terms in database output
$search_term = $_GET['search']; // Assuming search term is retrieved from user input
$search_term_escaped = htmlspecialchars($search_term, ENT_QUOTES, 'UTF-8'); // Escape search term
// Highlight search term in database output
$highlighted_output = str_ireplace($search_term_escaped, '<span class="highlighted">' . $search_term_escaped . '</span>', $database_output);
echo $highlighted_output;