php - Remove entire image if image source is within a specific directory -
i trying strip out html code of images content if image path within specific directory.
take example block of content:
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
what after is:
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
in example need have 2 images's removed contain /smilies/
, leave 1 img exists within /avatars/
path.
note alt="" in 2 different locations on 2 images matches.
<?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 $domelement) { $src = $domelement->getattribute('src'); if (strpos($src, $baseurl . $folder) !== false) { $removelist[] = $domelement; } } foreach ($removelist $toremove) { $toremove->parentnode->removechild($toremove); } $html = $dom->savehtml(); echo $html;
care have 2 separate foreach loops, can't remove domnode domnodelist iterating. problem casimir's answer think.
Comments
Post a Comment