更新:用正則表達式做它是不可靠的。 src =「..」或href =「..」語句可以是評論或javascript語句的一部分。爲了獲得可靠的鏈接,我建議使用XPath:
<?php
$html = file_get_contents('http://stackoverflow.com/questions/14782334/regex-expression-to-find-all-paths-in-a-html-string/14782594#14782594');
$doc = new DOMDocument();
@$doc->loadHTML($html);
$selector = new DOMXPath($doc);
$result = $selector->query('//a/@href | //@src');
foreach($result as $link) {
echo $link->value, PHP_EOL;
}
如果使用正則表達式我會盡力搶=在href或src屬性的"
之間的內容。這裏談到一個例子,如何從使用正則表達式獲得此鏈接頁面:
<?php
$html = file_get_contents('http://stackoverflow.com/questions/14782334/regex-expression-to-find-all-paths-in-a-html-string');
preg_match_all('/href="(?P<href>.*)"|src="(?P<src>.*)"/U', $html, $m);
<--- note the U to make the
pattern ungreedy
var_dump($m['href']);
var_dump($m['src']);
爲什麼不試着在'href =「'和下一個'''之間找到一切?這將*更容易和*更少*容易出錯。 – zerkms 2013-02-08 22:26:53
'href =「([^」] *)怎麼樣?''是否允許在URL中?我認爲空間實際上是...... – 2013-02-08 22:44:25
@P O'Conbhui:不允許使用空格,以及使用'「字符 – zerkms 2013-02-09 05:22:28