php - Replace words found in string with highlighted word keeping their case as found -
i want replace words found in string highlighted word keeping case found.
example
$string1 = 'there 5 colors'; $string2 = 'there 5 colors'; //replace 5 highlighted 5 $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
fivecolors
therefivecolors
expected output:
there
fivecolors
therefivecolors
how can done?
to highlight single word case-insensitively
use preg_replace() following regex:
/\b($p)\b/i explanation:
/- starting delimiter\b- match word boundary(- start of first capturing group$p- escaped search string)- end of first capturing group\b- match word boundary/- ending delimiteri- pattern modifier makes search case-insensitive
the replacement pattern can <span style="background:#ccc;">$1</span>, $1 backreference — contain matched first capturing group (which, in case, actual word searched for)
code:
$p = preg_quote($word, '/'); // pattern match $string = preg_replace( "/\b($p)\b/i", '<span style="background:#ccc;">$1</span>', $string ); to highlight 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
Post a Comment