将字符串中找到的单词替换为突出显示的单词,并保持其大小写不变 [英] Replace words found in string with highlighted word keeping their case as found

查看:115
本文介绍了将字符串中找到的单词替换为突出显示的单词,并保持其大小写不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用突出显示的单词替换字符串中找到的单词,并保持其大小写不变.

I want to replace words found in string with highlighted word keeping their case as found.

示例

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

当前输出:

five种颜色
five种颜色

There are five colors
There are five colors

预期输出:

five种颜色
Five种颜色

There are five colors
There are Five colors

这怎么办?

推荐答案

以不区分大小写的方式突出显示单个单词

在以下正则表达式中使用 preg_replace() :

/\b($p)\b/i

说明:

  • /-起始定界符
  • \b-匹配单词边界
  • (-第一个捕获组的开始
  • $p-转义的搜索字符串
  • )-第一个捕获组的结尾
  • \b-匹配单词边界
  • /-结束定界符
  • i-模式修饰符,使搜索不区分大小写
  • / - 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 delimiter
  • i - pattern modifier that makes the search case-insensitive

替换模式可以是<span style="background:#ccc;">$1</span>,其中$1是反向引用-它包含第一个捕获组所匹配的内容(在这种情况下,它是所搜索的实际单词)

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)

代码:

$p = preg_quote($word, '/');  // The pattern to match

$string = preg_replace(
    "/\b($p)\b/i",
    '<span style="background:#ccc;">$1</span>', 
    $string
);

> 查看实际效果

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

> 查看实际效果

这篇关于将字符串中找到的单词替换为突出显示的单词,并保持其大小写不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆