【问题标题】:preg_replace UNLESS string existspreg_replace 除非字符串存在
【发布时间】:2013-02-09 22:37:57
【问题描述】:

我正在尝试为所有超链接添加 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)

我已经四处寻找,如果有任何帮助,我将不胜感激。

【问题讨论】:

标签: php regex


【解决方案1】:

查找(也适用于 Notepad++)

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

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

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

【讨论】:

    【解决方案2】:

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

    例如,使用这些规则:

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

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

    【讨论】:

    • 谢谢,乔治。它正在生成一个用于电子邮件的模板,所以不幸的是所有 CSS 都需要内联
    猜你喜欢
    • 2012-04-10
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多