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 five colors
there five colors

expected output:

there five colors
there five colors

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 delimiter
  • i - 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 ); 

see in action


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); 

see in action


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -