Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

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

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

Expected output:

There are five colors
There are Five colors

How this can be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...