`
天梯梦
  • 浏览: 13635197 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

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
(
    [0] => Array
        (
            [0] => <a id="top8" href="http://list.mp3.baidu.com /song/A.htm?top8" class="p14" target="_top">歌曲列表</a>
            [1] => <a target="_blank" id="bp" href="http://ibtimes.com" class="p14">中文金曲榜</a>
            [2] => <a id="top19" href="http://africa.ibtimes.com/sections/companies/" class="p14" target="_top">轻音乐</a>
        )

    [1] => Array
        (
            [0] =>  id="top8" 
            [1] =>  target="_blank" id="bp" 
            [2] =>  id="top19" 
        )

    [2] => Array
        (
            [0] => http://list.mp3.baidu.com /song/A.htm?top8
            [1] => http://ibtimes.com
            [2] => http://africa.ibtimes.com/sections/companies/
        )

    [3] => Array
        (
            [0] =>  class="p14" target="_top"
            [1] =>  class="p14"
            [2] =>  class="p14" target="_top"
        )

    [4] => Array
        (
            [0] => 歌曲列表
            [1] => 中文金曲榜
            [2] => 轻音乐
        )

)
 

下面是我利用这个正则写的一个提取网页超链接及标题的函数:

 

function get_links($content) {
 $pattern = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
 preg_match_all($pattern, $content, $m);
 return $m;
}
 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics