正则表达式:如何不替换任何html标签中的特定单词? [英] Regex: How not to replace specific word in any html tag?

查看:51
本文介绍了正则表达式:如何不替换任何html标签中的特定单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以假设我有这样的文字:

So let's assume I have a text like this:

This is a great test! We're testing something awesome. Click here to <a href="whatever">test it!</a>.

我想在测试"一词中添加一些颜色,但是如果它在标签中,则不需要添加颜色.我尝试这样做:

I want to add some color to the word "test", but not if it's in an a tag. I've tried doing this:

/(?<!href="(.*?)">)test/

但是它不起作用.它是这样的:

But it doesn't work. It works like this:

/(?<!href="whatever">)test/

但是我当然有很多链接,所以这不是一个选择.

But of course I have many links, so this isn't an option.

整个代码如下:

$replacement = preg_replace('/(?<!href="SOLUTION HERE">)test/','<span style="color: #FF0000;">test</span>',$replacement);

预期结果:

This is a great <span style="color: #FF0000;">test</span>! We're <span style="color: #FF0000;">test</span>ing something awesome. Click here to <a href="whatever">test it!</a>.

推荐答案

与html字符串进行交互的快速,较不可靠的方法是使用正则表达式.DomDocument(或类似文件)是专门设计用来解析html的文件,它的可信度要高得多.我将发布正则表达式方式,如果可以管理它,则将添加DomDocument方式.

The quick, less reliable way to interact with html strings is with regex. DomDocument (or similar) is specially designed to parse html and is far more trustworthy. I'll post the regex way, and if I can manage it, I'll add a DomDocument way.

(* SKIP)(* FAIL)允许您匹配/使用和取消对子字符串的资格,然后在管道之后为实际要替换的子字符串编写模式.

(*SKIP)(*FAIL) allows you to match/consume and disqualify substrings then after the pipe you write the pattern for the substring that you actually want to replace.

模式:〜(?:< [^>] *&.; *?</[^>] *>(* SKIP)(* FAIL))| \ btest \ b〜s

替换:< span style ="color:#FF0000;"> \ 0</span>

模式演示

代码:( 演示)

$string="This is a great test! We're testing something awesome. Click here to <a href=\"whatever\">test it!</a>.";
$pattern='~(?:<[^>]*>.*?</[^>]*>(*SKIP)(*FAIL))|\btest\b~s';
$replace='<span style="color: #FF0000;">\0</span>';
echo preg_replace($pattern,$replace,$string);

输出:

This is a great <span style="color: #FF0000;">test</span>! We're testing something awesome. Click here to <a href="whatever">test it!</a>.

这篇关于正则表达式:如何不替换任何html标签中的特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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