$re = '/<(?\'Tag\'td|th)(?\'NonStyleAttributes1\'(?>\s+(?!style)\w*(?>="[^"<>]*")*)*)(?>(?\'SpaceBeforeStyle\'\s*)\sstyle="(?!padding|[^"<>]*\spadding)(?\'OtherStyling\'[^"<>]*)"(?\'NonStyleAttributes2\'(?>\s+(?!style)\w*(?>="[^"<>]*")*)*))?(?\'TagEnd\'\s*>)(?!\s*(?><br(?>\s[^<>])*\/?>\s*)?<\/\k\'Tag\'\s*>)/mi';
$str = 'This adds padding to table cells unless it already has padding, table cell is empty, or table cell only contains a <br> tag.
matching
<th>no attributes</th>
<td>no attributes</td>
<td id="1">* no style</td>
<td id="3" style="color:red;">*</td>
<td id="3" style="color:red;" title="boo">*</td>
<td id="3" style="color:red">*</td>
<td style="color:red;"><br><br></td>
non-matching
<tds>not td</tds>
<td id="n1" title="asdf" style="padding: 3px;">already padded</td>
<td style="unfinished
<td style="padding: 3px;">already padded, no other attributes</td>
<td style="color: red; padding: 3px;">already padded, no other attributes</td>
no matching because empty
<td />
<td></td>
<th></th>
<td style="color:red;"><br></td>
<td style="color:red;"><br/></td>
<td style="color:red;"><br /></td>';
$subst = "<${Tag}${NonStyleAttributes1}${SpaceBeforeStyle} style=\"padding: 3px;${OtherStyling}\"${NonStyleAttributes2}${TagEnd}>";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php