加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 在字符串中搜索单词并更改格式

发布时间:2020-12-13 17:47:59 所属栏目:PHP教程 来源:网络整理
导读:我不想通过php创建一个高亮标签搜索功能 当我搜索一部分单词时…整个单词都是彩色的 例如,这是一个示例文本: 文:英国监管机构表示,交易员使用私人在线聊天室来协调他们的买卖,以转移货币价格对他们有利. 当我搜索“th”时输出如下: 文:英国监管机构表示,
我不想通过php创建一个高亮标签搜索功能

当我搜索一部分单词时…整个单词都是彩色的

例如,这是一个示例文本:

文:英国监管机构表示,交易员使用私人在线聊天室来协调他们的买卖,以转移货币价格对他们有利.

当我搜索“th”时输出如下:

文:英国监管机构表示,以转移货币价格对他们有利.

所以…我试过这段代码……请帮我完成它.

这是一个算法:

$text= "British regulators say...";
foreach($word in $text)
{
  if( IS There "th" in $word)
   {
      $word2= '<b>'.$word.'</b>'
      replace($word with word2 and save in $text) 
   }
}

我怎么能用php语言呢?

解决方法

function highLightWords($string,$find)
{
   return preg_replace('/b('.$find.'w+)b/',"<b>$1</b>",$string); 
}

用法:

$string="British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.";
$find="th";
print_r(highLightWords($string,$find));

Fiddle

评论后编辑:

…How can I do it for middle characters? for example “line”

非常简单,只需相应地更新正则表达式

return preg_replace("/b(w*$findw*)b/",$string);

Fiddle

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读