【问题标题】:Regex expression to find all paths in a HTML string正则表达式查找 HTML 字符串中的所有路径
【发布时间】:2013-02-08 22:24:05
【问题描述】:

我有一个字符串,带有一个 htmlentities 编码的 HTML 代码。

我想要做的是找到 所有文档中的路径,介于:

href="XXX", src="XXX"。

我确实有一个正则表达式,可以找到所有以 http、https、ftp 和文件开头的链接,以免我重复它:

"/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]/i"

有什么想法吗?

【问题讨论】:

  • 为什么不尝试查找href=" 和下一个" 之间的所有内容?这将更加更容易并且更少容易出错。
  • href="([^" ]*)" 怎么样? URL 中是否允许使用 "?我认为空格实际上是......
  • @P O'Conbhui:不允许使用空格,以及" 字符

标签: php html regex


【解决方案1】:

更新:使用正则表达式并不可靠。 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']);

【讨论】:

    【解决方案2】:

    您可以使用 DOM 来查找特定标签中的所有链接。例如,要从锚标签中获取 url,请执行以下操作(未经测试,但它应该为您指明正确的方向):

    function findPaths($url)
    {
       $dom = new DOMDocument();
    
       //$url of page to search, the "@' is there to suppress warnings
       @$dom->loadHTMLFile($url) 
    
       $paths = array();
       foreach($dom->getElementsByTagName('a') as $path)
       {
         $paths[] = array('url' => $path->getAttribute('href'), text => $path->nodeValue);
       }
       return $paths;
    }
    

    您可以更轻松地使用 XPath 加载和评估 DOM。

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多