PHP

Highlight Search Term in Text

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Wrap every case-insensitive occurrence of a search term in <mark> tags for quick visual highlighting in search results. Properly escapes HTML so user input cannot inject markup.
PHP
Raw
<?php
function highlightTerm(string $text, string $term): string {
    if ($term === '') return htmlspecialchars($text, ENT_QUOTES);
    $escapedText = htmlspecialchars($text, ENT_QUOTES);
    $escapedTerm = htmlspecialchars($term, ENT_QUOTES);
    $pattern     = '/(' . preg_quote($escapedTerm, '/') . ')/iu';
    return preg_replace($pattern, '<mark>$1</mark>', $escapedText);
}

echo highlightTerm("PHP is great, PHP is fun.", "php");
// <mark>PHP</mark> is great, <mark>PHP</mark> is fun.
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.