PHP regex to check if image is wrapped with a tag -
i creating wordpress function , need determine whether image in content wrapped tag contains link pdf or doc file e.g.
<a href="www.site.com/document.pdf"><img src="../images/image.jpg" /></a>
how go doing php?
thanks
i very advise against using regular expression this. besides being more error prone , less readable, not give ability manipulate content easily.
you better of loading content domdocument, retrieving <img>
elements , validating whether or not parents <a>
elements. have validate whether or not value of href
attribute ends desired extension.
a crude implementation bit this:
<?php $shtml = <<<html <html> <body> <img src="../images/image.jpg" /> <a href="www.site.com/document.pdf"><img src="../images/image.jpg" /></a> <a href="www.site.com/document.txt"><img src="../images/image.jpg" /></a> <p>this text <a href="site.com/doc.pdf"> more text</p> </body> </html> html; $odoc = new domdocument(); $odoc->loadhtml($shtml); $onodelist = $odoc->getelementsbytagname('img'); foreach($onodelist $t_onode) { if($t_onode->parentnode->nodename === 'a') { $slinkvalue = $t_onode->parentnode->getattribute('href'); $sextension = substr($slinkvalue, strrpos($slinkvalue, '.')); echo '<li>i wrapped in anchor tag ' . 'and link ' . $sextension . ' file ' ; } } ?>
i'll leave exact implementation exercise reader ;-)
Comments
Post a Comment