2013-03-05 50 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