To highlight a single word case-insensitively
Use preg_replace()
with the following regex:
/($p)/i
Explanation:
/
- starting delimiter
- match a word boundary
(
- start of first capturing group
$p
- the escaped search string
)
- end of first capturing group
- 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(
"/($p)/i",
'<span style="background:#ccc;">$1</span>',
$string
);
See it in action
To highlight an array of words case-insensitively
$words = array('five', 'colors', /* ... */);
$p = implode('|', array_map('preg_quote', $words));
$string = preg_replace(
"/($p)/i",
'<span style="background:#ccc;">$1</span>',
$string
);
var_dump($string);
See it in action
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…