【问题标题】:Regex for HTML manipulation [closed]用于 HTML 操作的正则表达式 [关闭]
【发布时间】:2013-03-05 17:05:23
【问题描述】:

对于 any html td 中的 any 图像,为了得到以下结果,什么是正则表达式?

来自:

<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>

【问题讨论】:

  • Regex + HTML 是个坏主意。研究使用 DOM 解析器。
  • 我为您重新标记了此内容,希望能得到有效的回复。我对 XPath 不够熟练,但希望有人能给你更好的回应。
  • 谢谢 mkaatman,感谢您的建议。
  • DomDocument 不是巫毒教 :) 希望有帮助!
  • 这真的帮助了克里斯! :) 希望能报答你的帮助。

标签: php html regex xpath simplexml


【解决方案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

文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多