0

I'm trying to add CSS styling to all hyperlinks unless it has a "donttouch" attribute.

E.g.

  • Style this: <a href="http://whatever.com">style me</a>
  • Don't style this: <a href="http://whatever.com" donttouch>don't style me</a>

Here's my preg_replace without the "donttouch" exclusion, which works fine.

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

I've looked all over the place, and would appreciate any help.

Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • 7
    You may be better off using a real HTML parser for this. – icktoofay Feb 09 '13 at 22:42
  • @Arjan It's generating a template for use in an email, so CSS classes are unfortunately out of the question---all CSS has to be inline – skinnyandbald Feb 09 '13 at 22:46
  • 3
    [obligatory link to that one question that will explain everything](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Amelia Feb 09 '13 at 22:52

2 Answers2

0

Find (works also in Notepad++)

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

Replace with (Replace all in Notepad++):

\1<span style="whatever">\2</span></a>
Placido
  • 1,386
  • 1
  • 12
  • 24
0

This can be accomplished without a regular expression. Instead, use a CSS attribute selector.

For example, use these rules:

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

Technically, you are styling the elements with the 'donttouch' attribute, but you can use default values. This will be more efficient than attempting to use a regular expression to parse your HTML, which is usually a bad idea.

George Cummins
  • 28,485
  • 8
  • 71
  • 90