php拆词搜索,使用正则表达式用匹配项替换搜索词组或搜索词的php代码

我需要基于“火与水”这样的短语来突出显示我的网站内容.我需要把< b>在完全存在的词组周围加上标签.并且,如果单词单独出现(不是完整形式),则应该得到< b>.标签.例如,如果内容为:

The world is made of three elements fire and water and air. Fire is hot and water is wet.

结果应为:

The world is made of three elements ``fire and water`` ``and`` air. ``Fire`` is hot ``and`` ``water`` is wet.

我尝试使用:

$output = preg_replace("/("fire and water)/i", '``$1``', $content);

$output = preg_replace("/(fire|and|water)/i", '``$1``', $ouput);

然而,这产生了额外的(并且是不想要的)< b>.当整个短语出现在内容中时会产生如下标记:

``fire`` ``and`` ``water``

我知道这与在屏幕上显示的内容没有什么不同

``fire and water``

但是,当搜索短语包含“ /”时,会引起很大的问题.正则表达式中必须有一种方法可以突出显示完整的短语和单个单词,而不能一次执行.

解决方法:

该解决方案可能比您想象的要简单得多:

$input = 'The world is made of three elements fire and water and air. Fire is hot and water is wet.';

$output = preg_replace("/(fire and water|fire|and|water)/i", '$1',$input);

echo $output;

输出为:

The world is made of three elements fire and water and

air. Fire is hot and water is wet.

来源看起来像这样:

The world is made of three elements fire and water and air. Fire is hot and water is wet.

元素将按其顺序进行处理.

标签:html,php,regex

来源: https://codeday.me/bug/20191108/2009981.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值