Tuesday, April 7, 2009

Replacing CSS styles with inline style for rich email

Ever get frustrated when you use a "dreamweaver" style markup system, just to find that class definitions don't show up in certain email rendering environments?

The trick is to swap the declared classes for inline styles. I found another solution on the web that was way more complex than it needed to be, so here is a simpler way to do it:

note: in PHP and where $file is your HTML code:

// replace dreamweaver CSS class definitions with inline styles
if (preg_match("/class=/i", $file) ){
$wer = preg_match_all("/\.style[^\}]*\{*\}/i", $file, $hello);
foreach(array_unique($hello[0]) as $rest) {// rest is now the whole style class declaration
$rest=trim($rest);
$rest = str_replace("\n"," ",$rest);
preg_match_all("/\.style\S*.(?=\s+\{?)/i", $rest, $h2); // $h200 should now be just the .style45654 part
preg_match_all("/(?<=\{)[^}]*/i", $rest, $h3); // $h300 should now be just the definitions within the style
$styledef = trim ($h3[0][0]);
$simplestylename = trim ($h2[0][0]);
$simplestylename = str_replace('.','',$simplestylename);
$clssub = 'class="'.$simplestylename.'"';
$clsrp = 'style="'.$styledef .'"';
$file = str_replace($clssub,$clsrp,$file);
}
}

No comments: