2013-03-05 24 views
-5

是什么,才能有以下结果正则表达式的表达式,任何 HTML TD任何形象?正则表达式HTML操作

来自:

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

到:

<td width="7" height="50" nowrap background="/images/img_1.png"></td> 
+4

(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml- self-contained-tags/1732454#1732454) – 2013-03-05 17:07:31

+2

正则表达式+ HTML是一个坏主意。看看使用DOM解析器。 – 2013-03-05 17:08:27

+0

不要。只是...不。 – John 2013-03-05 17:09:20

回答

1

这是不好的做法,使用正则表达式来解析HTML。相反,使用PHP中提供的专门用于解析HTML的工具,即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(); 

看到它在行动:http://codepad.viper-7.com/x9ooyp

文档

+0

谢谢克里斯的时间,注意力和代码。你真的帮了我!我希望能够发挥作用。 – 2013-03-05 18:02:36