我有一个字符串,带有 htmlentities 编码的 HTML 代码。
我想做的是找到文档中的所有路径,介于:
href="XXX", src="XXX".
我确实有一个正则表达式可以找到所有以 http、https、ftp 和文件开头的链接,以免我重复它:
"/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i"
有什么想法吗?
最佳答案
更新:用正则表达式来做是不可靠的。 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 属性的 = "
之间的内容。这里有一个如何从 this 获取链接的示例使用正则表达式的页面:
<?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']);
关于php - 用于查找 HTML 字符串中所有路径的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14782334/