-1

I need help with regex pattern which will replace/get font size of first "span" before each table and use that span font-size in table style definition but span needs to be without close tag, not yet closed span tag.

from:

<span style="font-size:10px;">
<table>...</table>
</span>

to:

<span style="font-size:10px;">
<table style="font-size:10px;">...</table>
</span>

It needs to go all over and for each "table" that is inside some span with font size do same thing.

p3ro
  • 19
  • 3

1 Answers1

0

Don't use regex to parse html, use an html parser, something like PHP: DOMDocument, i.e.:

$html = <<< EOF
<span style="font-size:10px;">
<table>...</table>
</span>
EOF;

$dom = new DOMDocument(); # create DOMDocument
$dom->loadHTML($html); # Load $html into DOMDocument

foreach ($dom->getElementsByTagName('table') as $item) { # find all table elements in html

    $parent = $item->parentNode; # get parent node (<span>)
    $parent_style = $parent->getAttribute('style'); # get style attribute for parent node
    $item->setAttribute('style', $parent_style); # set $parent_style as style attribute
    echo $dom->saveHTML();
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • This is good example but my table uses font-size from span which contains this table, is there any way to get font size used in span style? I know it is not correct html syntax but that's how i get html. – p3ro Apr 20 '17 at 14:12
  • You need to get the `parent` element and use `getAttribute` to retrieve the value of `style`. I've updated my answer. – Pedro Lobito Apr 20 '17 at 14:16