preg_replace除非字符串存在


preg_replace UNLESS string exists

我正在尝试为所有超链接添加CSS样式,除非具有"donttouch"属性。

例如

  • 样式:<a href="http://whatever.com">style me</a>
  • 不设置样式:<a href="http://whatever.com" donttouch>don't style me</a>

这是我的preg_replace,没有"donttouch"排除,效果很好。

preg_replace('/<a(.*?)href="([^"]*)"(.*?)>(.*?)<'/a>/','<a$1href="$2"$3><span style="color:%link_color%; text-decoration:underline;">$4</span></a>', $this->html)

我到处都找过了,如果有任何帮助,我将不胜感激。

Find(也适用于Notepad++)

(?s)(<a (?:(?!donttouch)[^>])+>)(.*?)</a>

替换为(在Notepad++中全部替换):

'1<span style="whatever">'2</span></a>

这可以在没有正则表达式的情况下完成。相反,请使用CSS属性选择器。

例如,使用以下规则:

a { font-weight: bold; color: green }
a[donttouch=''] { font-weight: normal; color: blue }

从技术上讲,您使用"donttouch"属性设置元素的样式,但您可以使用默认值。这将比尝试使用正则表达式来解析HTML更有效,这通常是个坏主意。