Replace words found in string with highlighted word keeping their case as found

To highlight a single word case-insensitively

Use preg_replace() with the following regex:
/\b($p)\b/i
Explanation:
  • / - starting delimiter
  • \b - match a word boundary
  • ( - start of first capturing group
  • $p - the escaped search string
  • ) - end of first capturing group
  • \b - match a word boundary
  • / - ending delimiter
  • i - pattern modifier that makes the search case-insensitive
The replacement pattern can be <span style="background:#ccc;">$1</span>, where $1 is a backreference — it would contain what was matched by the first capturing group (which, in this case, is the actual word that was searched for)
Code:
$p = preg_quote($word, '/');  // The pattern to match

$string = preg_replace(
    "/\b($p)\b/i",
    '<span style="background:#ccc;">$1</span>', 
    $string
);

To highlight an array of words case-insensitively

$words = array('five', 'colors', /* ... */);
$p = implode('|', array_map('preg_quote', $words));

$string = preg_replace(
    "/\b($p)\b/i", 
    '<span style="background:#ccc;">$1</span>', 
    $string
);

var_dump($string);

Comments

Popular Posts