【问题标题】:PHP - How to extract achor href of specified linked image? [duplicate]PHP - 如何提取指定链接图像的 achor href? [复制]
【发布时间】:2015-04-22 00:39:00
【问题描述】:

如何根据图像 src 提取给定 HTML 的锚点 href?

例子:

<a href="http://idontneedthis.com"><img src="path/to/image/1.gif" /></a>
<a href="http://iwantthis.com"><img src="path/to/image/2.gif" /></a>
<a href="http://idontneedthisagain.com"><img src="path/to/image/3.gif" /></a>

在这种情况下,我需要使用2.gif 的 src 获取链接图像的链接。那将是具有 href http://iwantthis.com

的锚点

【问题讨论】:

  • 不,如果我知道 img src 的值,我想要 href 的值。
  • 查看第二个答案,即使用DOMDocument 的答案。那应该做你想做的事

标签: php regex parsing xpath extract


【解决方案1】:

这是一种可以利用 DOMXPath 来提取这些 @href 值的方法。

$doc = DOMDocument::loadHTML('
    <a href="http://idontneedthis.com"><img src="path/to/image/1.gif" /></a>
    <a href="http://iwantthis.com"><img src="path/to/image/2.gif" /></a>
    <a href="http://idontneedthisagain.com"><img src="path/to/image/3.gif" /></a>
');

$xpath = new DOMXPath($doc);
$links = $xpath->query('//a[img[contains(@src, "2.gif")]]');

foreach ($links as $link) {
   echo $link->getAttribute('href');
}

输出

http://iwantthis.com

【讨论】:

  • 除了正则表达式之外,OP 确实包含 xpath 标签,并且他没有具体说它必须与正则表达式一起使用。
  • @JohnMcMahon,更新了我没看到。
【解决方案2】:

使用正则表达式来解决这类问题是一个坏主意,并且可能会导致无法维护和不可靠的代码。最好给我们一个 HTML 解析器。

如果你还想使用正则表达式,你可以试试:

preg_match_all('%href="(.*?)".*?src="path/to/image/2\.gif"%i', $html, $match, PREG_PATTERN_ORDER);
$href = $match[1][0];
echo $href ;

输出:

http://iwantthis.com

【讨论】:

  • 您好,感谢您的发帖,但这不是我需要的。我只知道 img src 的值,据此我应该得到 href 值。
  • 所以,你需要相反,我会更新代码。
猜你喜欢
  • 2014-02-10
  • 2019-09-10
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 2012-09-16
  • 2021-10-09
  • 1970-01-01
相关资源
最近更新 更多