dstoiko
dstoiko

Reputation: 43

Regex search & replace inline CSS style

I need to search & replace inside HTML tags, CSS that was inlined, in order to avoid using the style="" attribute inline.

I.e. replace something that looks like this:

<table border="0" cellpadding="0" cellspacing="0" width="100%"  style="font-family: Helvetica;line-height: 100%;margin-top: 20px; text-align: left;vertical-align: bottom;color: #202020">

into something like that:

<table border="0" cellpadding="0" cellspacing="0" width="100%" font-family="Helvetica" line-height="100%" margin-top="20px" text-align="left" vertical-align="bottom" color="#202020">

Does someone know the regex for search & replace I would have to write in order to do that?

Thanks.

Upvotes: 3

Views: 6162

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627020

Use this regex replacement:

(?:\G(?!^)|\bstyle=")([^:]*):\s*([^;]*)[;"](?=[^>]*>)

Replace with (mind the space at the end):

$1="$2" 

Here is a demo

EXPLANATION

  • (?:\G(?!^)|\bstyle=") - A boundary where we'll start our matching. The boundary is the end of the previous match (\G(?!^)) or style=" (due to \bstyle=").
  • ([^:]*) - The 1st capturing group that holds a sequence of 0 or more characters other than :
  • : - a literal :
  • \s* - 0 or more whitespace
  • ([^;]*) - The 2nd capturing group that holds a sequence of 0 or more characters other than ;
  • [;"] - Either a ; or "
  • (?=[^>]*>) - We check the ending boundary to make sure we are inside a closing tag.

Upvotes: 5

Anders
Anders

Reputation: 8577

You could do it like this:

  1. Match style="(.*?)" and save the captured group to a variable.
  2. On that variable, match ([a-zA-Z-]+):\s*(.*?)\s*; and replace it with {1}="{2}".
  3. Replace style=".*?" with the result of number 2.

Upvotes: 5

Related Questions