我需要基于“火与水”这样的短语来突出显示我的网站内容.我需要把< 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