-5

What is the regex expression in order to have the following result, for any image inside any html td ?

from:

<td width="7" height="50" nowrap>
<img src="/images/img_1.png" width="7" height="50" alt="" />
</td>

to:

<td width="7" height="50" nowrap background="/images/img_1.png"></td>
Matt
  • 5,315
  • 1
  • 30
  • 57
André A.
  • 53
  • 6

1 Answers1

2

It is bad practice to use regular expressions to parse HTML. Instead, use the tools provided in PHP that are specifically geared toward parsing HTML, namely DomDocument[doc].

// create a new DomDocument object
$doc = new DOMDocument();

// load the HTML into the DomDocument object (this would be your source HTML)
$doc->loadHTML('
    <table>
        <tr>
            <td width="7" height="50" nowrap>
                <img src="/images/img_1.png" width="7" height="50" alt="" />
            </td>
        </tr>
    </table>
');

//Loop through each <td> tag in the dom 
foreach($doc->getElementsByTagName('td') as $cell) {
    // grab any images in this cell
    $images = $cell->getElementsByTagName('img');
    if ($images->length >= 1) { // if an image is found
        $image = $images->item(0);
        // add the 'background' property to the cell, use the 'src' property
        $cell->setAttribute('background', $image->getAttribute('src'));
        // remove the image
        $cell->removeChild($image);
    }
}
echo $doc->saveHTML();

See it in action: http://codepad.viper-7.com/x9ooyp

Documentation

Chris Baker
  • 49,926
  • 12
  • 96
  • 115