2009-10-15 67 views
0

我有此HTML代码(只是一个例子):提取文件名的regexp

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"><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. 

,我想更换所有<a class="nemo" ... </a>宽度这样的:使用javascript {图片src = emo_by_bebz_thumb.jpg}并定期表达。作为一个起点,我有这个表达式:

<a class=\"nemo\"[^>]*>(.*?)src="(.*?)"[^>]*></a> 

它的工作原理,但$ 2给出我只完整的图像路径和我只想要的文件名。有任何想法吗??

在此先感谢,

+0

你为什么用PHP标签呢? – 2009-10-15 16:45:36

+0

大概是因为这就是他用于任何剥离字符串的东西,并且将自己开放给利用PHP功能的解决方案,而不仅仅是一个原始的RegExp解决方案? – MattC 2009-10-15 16:51:52

回答

2

你应该得到它在$ 3如果你使用这个表达式:

<a class=\"nemo\"[^>]*>(.*?)src="(.*)\/(.*?)"[^>]*></a> 
0

的解决方案很简单:添加到您的正则表达式下面的指令,(字/伪代码),

Replace `<a class=\"nemo\"[^>]*>(.*?)src="(.*?)"[^>]*></a>` 
Ignore the first 5/and their content 
3

有没有什么说话反对使用真正的解析器呢?应该避免使用正则表达式来完成这样的工作。

这是一个很好的报道如何使用libxmlDOMDocument这个:Extracting data from HTML,由Kore Nordmann写的。

下面的代码是他的(没有太多的缺失,使其为你工作):

<?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); 
?> 
+2

+1,因为它确实是最好的解决方案 – 2009-10-15 16:57:11