PHP字符串操作:提取hrefs [英] PHP String Manipulation: Extract hrefs

查看:142
本文介绍了PHP字符串操作:提取hrefs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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="linkl.html">C - G</a>
<a title="G - K" href="link2.html">G - K</a>
<a title="K - M" href="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"

谢谢, 伊恩

推荐答案

您可以使用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="linkl.html">C - G</a>
<a title="G - K" href="link2.html">G - K</a>
<a title="K - M" href="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');
}

这篇关于PHP字符串操作:提取hrefs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆