2013-02-09 104 views
0

我試圖將CSS樣式添加到所有超鏈接除非它具有「donttouch」屬性。preg_replace除非存在字符串

E.g.

  • 風格這樣的:<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) 

我看遍了各地,並希望有任何幫助。

+7

爲此,您最好使用真正的HTML解析器。 – icktoofay 2013-02-09 22:42:49

+0

或者使用CSS類。 – Arjan 2013-02-09 22:45:36

+0

@Arjan它正在生成一個用於電子郵件的模板,所以CSS類不幸出現問題---所有的CSS都必須內聯 – skinnyandbald 2013-02-09 22:46:58

回答

0

查找(也工作在記事本++)

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

替換(在記事本中全部替換++):

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

這可沒有一個正則表達式來完成。相反,使用CSS屬性選擇器。

例如,使用這些規則:

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

從技術上說,你是用「donttouch」屬性造型的元素,但是你可以使用默認值。這將比試圖使用正則表達式來解析HTML更有效率,這通常是一個壞主意。

+0

謝謝喬治。它生成一個用於電子郵件的模板,所以不幸的是所有的CSS都需要內聯 – skinnyandbald 2013-02-10 20:45:51

相關問題