【问题标题】:PHP Regex HTML - Extract URLPHP 正则表达式 HTML - 提取 URL
【发布时间】:2023-03-27 18:24:02
【问题描述】:

我正在尝试使用正则表达式从 HTML 文件中提取多个 URL。 文件中还有其他 URL,我唯一的模式是“tableentries”。和“”

HTML 代码示例:

<tr class="tableentries2">
  <td>
    <a href="http://example.com/all-files/files/00000000789/">Click Here</a>
  </td>

我写的PHP:

$html = "value of the code above"
if(preg_match_all('/<td>.*</td>/', $html, $match)){
foreach($match[0] as $x){

echo $x . "<br>";

}}

【问题讨论】:

  • 您的问题到底是什么?这段代码能给你带来什么?为什么它不起作用?
  • HTML 属性周围缺少引号。 &lt;tr class="tableentries2"&gt; ... &lt;a href="http://example.com/..."&gt;(编辑你的问题)
  • 也许可以使用像simplehtmldom.sourceforge.net这样的DOM解析器

标签: php html regex


【解决方案1】:

为什么不只查找href 值? (已更新,因为编辑后的代码现在有引号。)

preg_match_all('/href="([^\s"]+)/', $html, $match);

那么 URI 将位于 $match[1][0]

【讨论】:

  • 问题是页面上还有其他 URL,所以我唯一的模式是“tableentries”。以及 URL 后面的开头和“”。感谢您的帮助!
【解决方案2】:

你真的不应该使用正则表达式来解析 HTML。 DOMDocument 实际上很容易用于这种类型的事情。这是一个简单的例子。

<?php
error_reporting(E_ALL);
$html = "
<table>
    <tr>
        <td>
            <a href='http://www.test1-1.com'>test1-1</a>
        </td>
        <td>
            <a href='http://www.test1-2.com'>test1-2</a>
        </td>
        <td>
            <a href='http://www.test1-3.com'>test1-3</a>
        </td>
    </tr>
    <tr>
        <td>
            <a href='http://www.test2-1.com'>test2-1</a>
        </td>
        <td>
            <a href='http://www.test2-2.com'>test2-2</a>
        </td>
        <td>
            <a href='http://www.test2-3.com'>test2-3</a>
        </td>
    </tr>
</table>";

$DOM = new DOMDocument();
//load the html string into the DOMDocument
$DOM->loadHTML($html);
//get a list of all <A> tags
$a = $DOM->getElementsByTagName('a');
//loop through all <A> tags
foreach($a as $link){
    //echo out the href attribute of the <A> tag.
    echo $link->getAttribute('href').'<br />';
}
?>

这将输出:

http://www.test1-1.com
http://www.test1-2.com
http://www.test1-3.com
http://www.test2-1.com
http://www.test2-2.com
http://www.test2-3.com

【讨论】:

  • 问题是页面上还有其他 URL,所以我唯一的模式是“tableentries”。以及 URL 后面的开头和“”。感谢您的帮助!
  • 如何同时获取链接的 test1-2 标题?
  • @thevoipman 您可以使用 nodeValue 属性。类似$link-&gt;nodeValue。这是一个例子:codepad.viper-7.com/JBsfP1
【解决方案3】:
<?php
preg_match_All("#<a\s[^>]*href\s*=\s*[\'\"]??\s*?(?'path'[^\'\"\s]+?)[\'\"\s]{1}[^>]*>(?'name'[^>]*)<#simU", $html, $hrefs, PREG_SET_ORDER);

foreach ($hrefs AS $urls){
 print $urls['path']."<br>";
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多