PHP 字符串操作:提取 href
我有一个 HTML 字符串,我想检查它里面是否有任何链接,如果有,则提取它们并将它们放入一个数组中。我可以在 jQuery 中通过其简单的选择器来完成此操作,但我找不到在 PHP 中使用的正确方法。
例如,该字符串可能如下所示:
<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>
How (in PHP) can i put it into an array that isn't like:
[1]=>"link1.html"
[2]=>"link2.html"
[3]=>"link3.html"
谢谢, 伊恩
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>
How (in PHP) can i turn it into an array that looks something like:
[1]=>"link1.html"
[2]=>"link2.html"
[3]=>"link3.html"
Thanks,
Ian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 PHP 的
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 thehref
attribute from a string of HTML.你的问题很难理解,但我相信你想要一个 PHP DOM 解析器,你可以在这里找到简单的 dom 解析器: http:// simplehtmldom.sourceforge.net/ 一个小的用法示例是:
你可以使用 jQuery 那么你应该能够使用它,没有问题,因为它的选择系统与 jQuery 以及 CSS 相同,因为 jQuery 源自 CSS
Your question is diffucult to understand but i believe you want a PHP DOM Parser, you can find simple dom parser here: http://simplehtmldom.sourceforge.net/ and a small usage example is:
you you can use jQuery then you should be able to use this no problem as its selecting system is the same as jQuery aswell as CSS, as jQuery derives from CSS
一条线解决方案
One line solution
如果格式始终相同,您可能可以使用explode和strip_tags的组合来对其进行排序,例如
if the format is always the same, u can probably sort it out with a combination of explode and strip_tags something like