更新:用正则表达式做它是不可靠的。 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