Extract filename from HTML text using regexp
I have this HTML code (just an example):
Sem vestibulum blandit nostra, nullam imperdiet, pellentesque vel wisi sit fusce purus mi, porttitor lorem. Bibendum non phasellus ut ipsum massa sed, interdum per, facilisis facilis luctus fermentum et donec, tristique tristique non.</p>
<p align="justify">开发者_JS百科<a class="nemo" href="http://myserver.com/images/blogs/65/emo_by_bebz.jpg"><img style="max-width:256px; max-height:256px" src="http://myserver.com/images/blogs/65/emo_by_bebz_thumb.jpg" alt="" /></a></p>
<p align="justify">Ante sed pede adipiscing morbi, ut aliquam orci, nunc tempus lectus suspendisse, sem at sit ullamcorper augue.
and i want to replace all <a class="nemo" ... </a>
width this: {image src=emo_by_bebz_thumb.jpg} using javascript and a regular expresion. As a starting point i have this regex:
<a class=\"nemo\"[^>]*>(.*?)src="(.*?)"[^>]*></a>
it works, but $2 gives me only the full image path and i only want the filename. Any ideas??
thanks in advance,
Is there anything that speaks against using a real parser for this? Regex should be avoided for such a job.
Here is a nice write-up how to use libxml
and DOMDocument
for this: Extracting data from HTML, written by Kore Nordmann.
The following code is his (there's not much missing to make it work for you):
<?php
$oldSetting = libxml_use_internal_errors( true );
libxml_clear_errors();
$html = new DOMDocument();
$html->loadHtmlFile( 'http://kore-nordmann.de/blog.html' );
$xpath = new DOMXPath( $html );
$links = $xpath->query( '//a' );
foreach ( $links as $link )
{
echo $link->getAttribute( 'href' ), "\n";
}
libxml_clear_errors();
libxml_use_internal_errors( $oldSetting );
?>
You should get it in $3 if you use this regex:
<a class=\"nemo\"[^>]*>(.*?)src="(.*)\/(.*?)"[^>]*></a>
The solution is very simple: add to your regex the following instruction, (in words / pseudo code),
Replace `<a class=\"nemo\"[^>]*>(.*?)src="(.*?)"[^>]*></a>`
Ignore the first 5 / and their content
精彩评论