【问题标题】:Regex How to extract link from HTML with specific path正则表达式如何从具有特定路径的 HTML 中提取链接
【发布时间】:2017-09-11 15:56:26
【问题描述】:

我一直在尝试使用正则表达式提取具有特定 URL 的链接,但失败了我尝试使用下面的正则表达式使用 PHP 提取链接。

preg_match_all('/\\<a href="(.*?)\\">/', $data1, $matches);

HTML 在这里只是一个 sn-p

<a href="https://www.website.com/n/?confirm.php" ></a>

整个html包含很多链接我需要这个链接。

【问题讨论】:

  • 提取所有 URL(首选方法是 DOM),然后尝试使用preg_grep 输出包括特定部分的 URL。
  • @revo 按照你的方式有什么答案吗?
  • 你真正想要实现什么,你能扩展你的问题吗?是否要获取具有特定 URL 的锚标记的属性?
  • @siniradam 我其实只想要锚标签的链接

标签: php html regex


【解决方案1】:

如果我没有误解你的问题,这将起作用。

$html = '<a href="https://www.website.com/n/?confirm.php" ></a>';
preg_match_all('/href="([^\s"]+)/', $html, $match);
print '<pre>';
print_r($match);
print '</pre>';
print $match[1][0];

已编辑:根据评论,您没有向我们提供具体的网址,这就是为什么我只是发布一个通用答案来捕获href。现在看我下面的答案。使用的正则表达式可以在这里找到https://regex101.com/r/pnfz7E/1

$re = '/<a href="([^"]*?\/n\/\?confirm\.php)">.*?<\/a>/m';
$str = '<a href="https://www.website.com/n/?noconfirm.php">SSD</a>
<div>How are you</div>
<a href="https://www.website.com/n/?confirm.php">HDD</a>
<h2>Being Sunny</h2>
<a href="https://www.ltmgtfu.com/n/?noconfirm.php">MSD</a>
<div>How are you</div>
<a href="https://www.website.com/n/?confirm.php"></a>
<h2>Being Sunny</h2>
<a href="https://www.google.com/n/?noconfirm.php">GSD</a>
<div>How are you</div>
<a href="https://www.website.com/n/?confirm.php">LSD</a>
<h2>Being Sunny</h2>';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
print '<pre>';
print_r($matches);
print '</pre>';

【讨论】:

  • 它将打印所有的锚标签,我更具体来说是 /n/?confirm.php。
  • @OwaisIqbal 看看我编辑的答案。我希望它对你有用。
猜你喜欢
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 2014-05-30
  • 1970-01-01
相关资源
最近更新 更多