2012-12-13 132 views
0

我有我想在我的項目中使用的網頁源代碼。我想在此代碼中使用圖像鏈接。所以,我想在PHP中使用正則表達式來訪問這個鏈接。使用正則表達式找到字符串的子串

就是這樣:

IMG SRC = 「http://imagelinkhere.com」 級= 「形象」

只有一個這樣的行。 我的邏輯是獲得= 「圖像 」

字符

=「

」 級之間的字符串。

我該怎麼做REGEX?非常感謝你。

+0

不使用正則表達式來解析HTML http://stackoverflow.com/questions/1732348/regex-match-open-tags-除-xhtml-self-contained-tags/1732454#1732454 – 2012-12-13 09:13:30

回答

3

Don't use Regex for HTML .. try DomDocument

$html = '<html><img src="http://imagelinkhere.com" class="image" /></html>'; 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 
$img = $dom->getElementsByTagName("img"); 

foreach ($img as $v) { 
    if ($v->getAttribute("class") == "image") 
     print($v->getAttribute("src")); 
} 

輸出

http://imagelinkhere.com 
+0

問題是,此代碼中有30或40張圖片。我想使用其中的一個,而不是全部。 最後沒有「class =」image「,只有一個有,我想用那個,這就是爲什麼我在=」和「class =」image「字符之間說,想用正則表達式 –

+0

你可以添加填充HTML到http://pastbin.com ..以便我可以有一個想法你想要什麼..我仍然相信它可以完成與DomDocument – Baba

+0

當然,這是代碼。 pastebin.com/qBN7K7xe 這就是我想要得到的鏈接: http://i.milliyet.com.tr/YeniAnaResim/2012/12/12/ruzgar-enerjisiyle-mayini-imha-ediyor-2869627。 Jpeg –

-1

嘗試使用preg_match_all,像這樣:

preg_match_all('/img src="([^"]*)"/', $source, $images); 

那應該把所有的圖像的URL的在$images變量。正則表達式的作用是找到代碼中的所有img src位,並匹配引號之間的位。

0

有幾種方法可以做到這一點:

1.you可以使用 SimpleHTML DOM解析器,我用簡單的HTML喜歡

2.you也可以使用的preg_match

$foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" class="image" />'; 
$array = array(); 
preg_match('/src="([^"]*)"/i', $foo, $array) ; 

thread

1

使用

.*="(.*)?" .* 

with preg replace只給出第一個正則表達式組(\ 1)中的url。

如此完整,將看起來像

$str='img src="http://imagelinkhere.com" class="image"'; 
$str=preg_replace('.*="(.*)?" .*','$1',$str); 
echo $str; 

- >

http://imagelinkhere.com 

編輯: 或者只是跟着爸爸的建議,使用DOM解析器。我會記住,正則表達式在解析html時會讓你頭疼。

1
preg_match("/(http://+.*?")/",$text,$matches); 
var_dump($matches); 

鏈接將在$匹配。

0

我能聽到馬蹄聲,所以我已經與DOM解析,而不是正則表達式。

$dom = new DOMDocument(); 
$dom->loadHTMLFile('path/to/your/file.html'); 
foreach ($dom->getElementsByTagName('img') as $img) 
{ 
    if ($img->hasAttribute('class') && $img->getAttribute('class') == 'image') 
    { 
     echo $img->getAttribute('src'); 
    } 
} 

這將僅呼應img標籤的src屬性與class="image"

相關問題