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;
}
 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值