2009-10-15 68 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