I want to replace words found in string with highlighted word keeping their case as found.
Example
$string1 = 'There are five colors';
$string2 = 'There are Five colors';
//replace five with highlighted five
$word='five';
$string1 = str_ireplace($word, '<span style="background:#ccc;">'.$word.'</span>', $string1);
$string2 = str_ireplace($word, '<span style="background:#ccc;">'.$word.'</span>', $string2);
echo $string1.'<br>';
echo $string2;
Current output:
There are
five
colors
There arefive
colors
Expected output:
There are
five
colors
There areFive
colors
How this can be done?
To highlight a single word case-insensitively
Use
preg_replace()
with the following regex: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 delimiteri
- pattern modifier that makes the search case-insensitiveThe 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:
See it in action
To highlight an array of words case-insensitively
See it in action
str_replace - case sensitive
str_ireplace - class insenstive
http://www.php.net/manual/en/function.str-replace.php
http://www.php.net/manual/en/function.str-ireplace.php
Here is the test case.
Results