木一 发表于 2017-4-8 11:59:30

PHP正则表达式提取超链接及其标题

  关联:





PHP正则表达式






PHP正则表达式提取超链接及其标题

  今天在做一个使用PHP正则提取文章链接及标题的插件时遇到一个问题,自己写出的正则总是很难完整无误的把想要的结果提取出来,于是到网站
搜索一番,终于找到一个短小精悍的正则,功能却一点都不含糊。





/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i
  下面是一个例子:



<?php
$str = '<a id="top8" href="http://list.mp3.baidu.com /song/A.htm?top8" class="p14" target="_top">歌曲列表</a><br><a target="_blank" id="bp" href="http://ibtimes.com" class="p14">中文金曲榜</a><br><a id="top19" href="http://africa.ibtimes.com/sections/companies/" class="p14" target="_top">轻音乐</a></td>';
$pat = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';   
preg_match_all($pat, $str, $m);
print_r($m);
  输出结果为:



Array
(
=> Array
(
=> <a id="top8" href="http://list.mp3.baidu.com /song/A.htm?top8" class="p14" target="_top">歌曲列表</a>
=> <a target="_blank" id="bp" href="http://ibtimes.com" class="p14">中文金曲榜</a>
=> <a id="top19" href="http://africa.ibtimes.com/sections/companies/" class="p14" target="_top">轻音乐</a>
)
=> Array
(
=>id="top8"
=>target="_blank" id="bp"
=>id="top19"
)
=> Array
(
=> http://list.mp3.baidu.com /song/A.htm?top8
=> http://ibtimes.com
=> http://africa.ibtimes.com/sections/companies/
)
=> Array
(
=>class="p14" target="_top"
=>class="p14"
=>class="p14" target="_top"
)
=> Array
(
=> 歌曲列表
=> 中文金曲榜
=> 轻音乐
)
)
   下面是我利用这个正则写的一个提取网页超链接及标题的函数:



function get_links($content) {
$pattern = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
preg_match_all($pattern, $content, $m);
return $m;
}
 
页: [1]
查看完整版本: PHP正则表达式提取超链接及其标题