找到包含图像的<p>并更改</p> <p>的样式

时间:2015-06-19 22:20:17

标签: php dom

我正在通过PHP解析Wordpress后发布HTML。我希望所有图像都居中。仅此一点很容易,但是,我也希望同一行上的图像能够集中在一起。为此,我需要将属性class="image-content"应用于<p>块。

如何使用PHP执行此操作?

这是帖子在编辑器中的样子:

enter image description here

这是Wordpress为这篇文章提供的HTML:

<p>Single line paragraph.</p>
<p>
    <a href="image.png">
        <img class="alignnone wp-image-39 size-thumbnail" src="image.png" width="150" height="150" />
    </a>
</p>
<p>
    Multi line paragraph which is a multi line paragraph 
    which is a multi line paragraph which is a multi line 
    paragraph which is a multi line paragraph which is a 
    multi line paragraph which is a multi line paragraph 
    which is a multi line paragraph which is a multi line
     paragraph which is a multi line paragraph which is a 
     multi line paragraph which is a multi line paragraph 
     which is a multi line paragraph which is a multi line 
     paragraph which is a multi line paragraph which is a 
     multi line paragraph which is a multi line paragraph.
</p>
<p>
    <a href="image.png">
        <img class="alignnone wp-image-39 size-thumbnail" src="image.png" width="150" height="150" />
    </a>
    <a href="image.png">
        <img class="alignnone wp-image-39 size-thumbnail" src="image.png" width="300" height="300" />
    </a>
</p>
<p>End of post.</p>

1 个答案:

答案 0 :(得分:1)

您可以使用DOMDocument,xpath和简单替换来完成此操作。

    $parse = new \DOMDocument();
    $parse->loadHTML($html);

    $xpath = new \DOMXpath($parse);
    $images = $xpath->query('//p//img');

    $re = "/(.*)/";
    $subst = "$1 image-content";

    foreach ($images as $image) {
        $class = preg_replace($re, $subst, $image->getAttribute('class'), 1);
        $image->setAttribute('class',$class);
    }

    $htmlFinal = $parse->saveHTML();

修改

如果要将类附加到包含p元素,可以像这样使用它:

    $parse = new \DOMDocument();
    $parse->loadHTML($html);

    $xpath = new \DOMXpath($parse);
    $ps = $xpath->query('//p');

    foreach ($ps as $p) {
        if ($p->getElementsByTagName('img')->length > 0) $p->setAttribute('class', 'image-content');           
    }

    $htmlFinal = $parse->saveHTML();

如果p标签在解析Dom之前可能有一个类集,则应该将这两个示例组合起来添加新类而不是仅设置它。