如果图像源位于特定目录中,则删除整个图像

时间:2013-08-10 01:44:42

标签: php preg-replace

如果图像路径在特定目录中,我试图从内容中删除任何html图像代码。

以此块内容为例:

Donec iaculis <img src="http://www.domain.tld/smilies/butterfly.gif" alt="butterfly.gif" /> arcu pretium elementum et posuere felis. <img alt="mrgreen.gif" src="http://www.domain.tld/smilies/mrgreen.gif" /> Duis sit amet erat vitae tellus eleifend varius. <img src="http://www.domain.tld/avatars/somedude.jpg" /> Pellentesque ac ligula

我所追求的是:

Donec iaculis arcu pretium elementum et posuere felis. Duis sit amet erat vitae tellus eleifend varius. <img src="http://www.domain.tld/avatars/somedude.jpg" /> Pellentesque ac ligula

在此示例中,我需要删除包含/smilies/的两个图像,并保留/avatars/路径中存在的一个图像。

请注意,alt =“”位于匹配的两个图像上的两个不同位置。

2 个答案:

答案 0 :(得分:0)

使用DOM的示例:

$doc = new DOMDocument();
@$doc->loadHTML($yourHTML);
foreach($doc->getElementsByTagName('img') as $imgNode) {
    if (strpos('/smilies/', $imgNode->getAttribute('src')))
        $imgNode->parentNode->removeChild($imgNode);
}
$yourHTML = $doc->saveHTML();

答案 1 :(得分:0)

<?php
$html = 'Donec iaculis magna eget <img src="http://www.domain.tld/smilies/butterfly.gif" alt="butterfly.gif" /> arcu pretium elementum et posuere felis. Vivamus eget sodales lorem, id dictum lorem. Nunc vitae facilisis nibh. Integer dignissim, diam non molestie luctus, libero lacus auctor eros, vel hendrerit lorem risus vel elit. Pellentesque ac magna nec lectus tristique blandit. <img src="http://www.domain.tld/smilies/mrgreen.gif" /> Duis sit amet erat vitae tellus eleifend varius. <img src="http://www.domain.tld/avatars/somedude.jpg" /> Pellentesque ac ligula eget lacus dapibus fermentum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Morbi gravida tempor leo eget lacinia. Curabitur interdum diam in congue consequat.';

$baseurl = 'http://www.domain.tld';
$folder = '/smilies/';

$dom = new domDocument;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagname('img');
$removeList = array();
foreach ($images as $domElement) {
    $src = $domElement->getAttribute('src');
    if (strpos($src, $baseurl . $folder) !== false) {
        $removeList[] = $domElement;
    }
}

foreach ($removeList as $toRemove) {
    $toRemove->parentNode->removeChild($toRemove);
}

$html = $dom->saveHTML();

echo $html;

请注意,您必须执行两个单独的foreach循环,因为您无法从正在迭代的DOMNodeList中删除DOMNode。这也是我认为卡西米尔的答案的问题。