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="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"
谢谢, 伊恩
正确答案
您可以使用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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20