• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

PHP字符串操作:提取hrefs

用户头像
it1352
帮助1

问题说明

我有一个HTML字符串,我想检查一下其中是否有任何链接,如果有,请将其提取出来并将它们放入数组中.我可以使用其选择器的简单性在jQuery中进行此操作,但是我找不到在PHP中使用的正确方法.

I have a string of HTML that I would like to check to see if there are any links inside of it and, if so, extract them and put them in an array. I can do this in jQuery with the simplicity of its selectors but I cannot find the right methods to use in PHP.

例如,字符串可能如下所示:

For example, the string may look like this:

<h1>Doctors</h1>
<a title="C - G" href="https://www.it1352.com/linkl.html">C - G</a>
<a title="G - K" href="https://www.it1352.com/link2.html">G - K</a>
<a title="K - M" href="https://www.it1352.com/link3.html">K - M</a>

如何(在PHP中)如何将其转换为类似于以下内容的数组:

How (in PHP) can i turn it into an array that looks something like:

[1]=>"link1.html"
[2]=>"link2.html"
[3]=>"link3.html"

谢谢, 伊恩

正确答案

#1

您可以使用PHPs DOMDocument库来解析XML和/或HTML.如下所示的方法应该可以解决问题,以便从HTML字符串中获取href属性.

You can use PHPs DOMDocument library to parse XML and/or HTML. Something like the following should do the trick, to get the href attribute from a string of HTML.

$html = '<h1>Doctors</h1>
<a title="C - G" href="https://www.it1352.com/linkl.html">C - G</a>
<a title="G - K" href="https://www.it1352.com/link2.html">G - K</a>
<a title="K - M" href="https://www.it1352.com/link3.html">K - M</a>';

$hrefs = array();

$dom = new DOMDocument();
$dom->loadHTML($html);

$tags = $dom->getElementsByTagName('a');
foreach ($tags as $tag) {
       $hrefs[] =  $tag->getAttribute('href');
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkhab
系列文章
更多 icon
同类精品
更多 icon
继续加载