2014-10-12 47 views
0

我想從html源代碼使用以下正則表達式的圖像網址,但它失敗時,圖像的網址中有空格。例如,這個網址:preg_match_all正則表達式失敗時,有空格

<img src="http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Entertainment/876/493/kazantsev pink bikini reuters.jpg?ve=1&amp;tl=1" alt="kazantsev pink bikini reuters.jpg" itemprop="image"> 

$image_regex_src_url = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui'; 
preg_match_all($image_regex_src_url, $string, $out, PREG_PATTERN_ORDER); 

這讓我回到以下。
http://a57.foxnews.com/global.fncstatic.com/static/managed/img/Entertainment/876/493/kazantsev

有沒有辦法匹配任何字符,包括空格?或者是我必須在php配置中設置的東西?

+0

'。*'也包含空格。問題不在這裏,正則表達式工作正常。顯示您正在嘗試應用的文字。這可能會發生,沒有空格,但'''或'''(他們不應該在URL中) – Cheery 2014-10-12 00:18:11

+0

你可以簡化你的正則表達式:' 2014-10-12 00:31:56

+0

I'm trying to post the string here to see if there's some other reason it won't work, but I'm having trouble with stackoverflow truncating it, is there a tag I can put in the comments when pasting in code? kazantsev pink bikini reuters.jpg techdog 2014-10-12 00:50:18

回答

1

您的正則表達式有幾個問題。

首先,您嘗試使用連接運算符('.')將表達式的兩個部分連接在一起(,這不是必需的)。其次,你不需要在你的角色類中使用替換運算符|

.將匹配除換行符之外的任何字符。這些標籤可能包含換行符,因爲它們位於HTML源代碼中。您可以使用s(dotall)修飾符,該修飾符強制該點匹配包括換行符在內的任何字符,或使用否定字符類,意思是匹配除之外的任何字符

使用sDOTALL)修改器:

$image_regex_src_url = '/<img[^>]*src=(["\'])(.*?)\1/si'; 

使用否定的字符類[^ ]

$image_regex_src_url = '/<img[^>]*src=(["\'])([^"\']*)\1/i'; 

雖然,它是非常容易使用的解析器,例如DOM搶結果。

$doc = new DOMDocument; 
@$doc->loadHTML($html); // load the HTML 

foreach($doc->getElementsByTagName('img') as $node) { 
    $urls[] = $node->getAttribute('src'); 
} 

print_r($urls); 
+0

這更好,我會嘗試後我修復了第一個問題,謝謝 – techdog 2014-10-12 00:52:08

+0

感謝您爲清理正則表達式以及替代方法,這個方法更加簡潔和可能更快,並且非常感謝您的理解,以供將來參考,如何將s( dotall)modifier – techdog 2014-10-12 01:15:57

+0

再次感謝,我將用你建議的dom解決方案重新編寫代碼。 – techdog 2014-10-12 01:23:26