任意のhtmltd内の任意の画像に対して、次の結果を得るための正規表現は何ですか?
から:
<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>
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
ドキュメンテーション
DomDocument
- http://php.net/manual/en/class.domdocument.phpDomElement
- http://www.php.net/manual/en/class.domelement.phpDomElement::getAttribute
- http://www.php.net/manual/en/domelement.getattribute.phpDOMElement::setAttribute
- http://www.php.net/manual/en/domelement.setattribute.phpDomDocument::loadHTMLFile
- http://www.php.net/manual/en/domdocument.loadhtmlfile.php