0

I've got HTML code like below:

<p style="text-align: center; width: 200px">Hellow world</p>
<table style="width: 500px; font-family: Arial; font-size: 18px">
  <td style="width: 20px; color: red">One</td>
  <td style="width: 50px; color: green">Two</td>
  <td style="width: 100px; color: blue">Three</td>
</table>

I need preg_replace pattern for PHP that will remove only width property from all tags (td, tr, thead, tbody) inside table.

<p style="text-align: center; width: 200px">Hellow world</p>
<table style="font-family: Arial; font-size: 18px">
  <td style="color: red">One</td>
  <td style="color: green">Two</td>
  <td style="color: blue">Three</td>
</table>

So far I come up with this:

// deleting style attribute from table    
$sHtml = preg_replace('%<table[^>]*?style\s*=\s*"[^"]*"[^>]*>(.*?)</table>%si', '<table>$1</table>', $sHtml);
// deleting style attribute from td
$sHtml = preg_replace('%<td[^>]*?style\s*=\s*"[^"]*"[^>]*>(.*?)</td>%si', '<td>$1</td>', $sHtml);

Which deletes all whole style property inside table and tds:

<p style="text-align: center; width: 200px">Hellow world</p>
<table>
   <td>One</td>
   <td>Two</td>
   <td>Three</td>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • Possibly duplicate of https://stackoverflow.com/questions/3026096/remove-all-attributes-from-an-html-tag. – vimalDev Apr 06 '18 at 04:42
  • 1
    Possible duplicate of [Remove all attributes from an html tag](https://stackoverflow.com/questions/3026096/remove-all-attributes-from-an-html-tag) – Prashant Pokhriyal Apr 06 '18 at 04:59

1 Answers1

2

Try this

// deleting style attribute from table    
$sHtml = preg_replace('/(<table|tr|td|tbody|thead)(.*)(width: [0-9]+px;)/i', '$1$2', $sHtml);