2012-11-24 16 views
-3

如何使用「preg_replace」查找所有圖像鏈接?我一直很難理解如何實現正則表達式使用preg_replace在頁面上查找所有圖像

是我到目前爲止已經試過:

$pattern = '~(http://pics.-[^0-9]*.jpg)(http://pics.-[^0-9]*.jpg)(</a>)~'; 
$result = preg_replace($pattern, '$2', $content); 
+0

爲更好地理解添加示例...您現在有一個示例鏈接,並且您想要一個... – NazKazi

+1

http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html -with-php – nhahtdh

+1

正則表達式不是一切的最終解決方案。 – 2012-11-24 13:04:55

回答

3

preg_replace(),顧名思義,替換的東西。您想使用preg_match_all()

<?php 
// The \\2 is an example of backreferencing. This tells pcre that 
// it must match the second set of parentheses in the regular expression 
// itself, which would be the ([\w]+) in this case. The extra backslash is 
// required because the string is in double quotes. 
$html = "<b>bold text</b><a href=howdy.html>click me</a>"; 

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); 

foreach ($matches as $val) { 
    echo "matched: " . $val[0] . "\n"; 
    echo "part 1: " . $val[1] . "\n"; 
    echo "part 2: " . $val[2] . "\n"; 
    echo "part 3: " . $val[3] . "\n"; 
    echo "part 4: " . $val[4] . "\n\n"; 
} 
2

另一種簡單的方法來查找所有圖片來自網頁的鏈接,使用簡單的HTML DOM解析器

// URL從創建DOM或文件

$html = file_get_html('http://www.google.com/'); 

//查找所有圖片

foreach($html->find('img') as $element) 
echo $element->src . '<br>'; 

這是如此簡單的方式來獲得從任何網頁的所有圖像鏈接。

+0

+1。如果您對網頁中更復雜的結構感興趣,絕對是您的選擇。 – Flavius

相關問題