Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 950
dstoiko Avatar asked Feb 18 '26 14:02

dstoiko


1 Answers

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.
like image 140
Wiktor Stribiżew Avatar answered Feb 20 '26 06:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!