当前位置: 首页 > 图文教程 > 网络编程 > PHP > PHP正则表达式提取超链接及其标题

PHP
《PHP设计模式介绍》第十三章 适配器模式
《PHP设计模式介绍》第十四章 动态记录模式
《PHP设计模式介绍》第十五章 表数据网关模式
《PHP设计模式介绍》第十六章 数据映射模式
《PHP设计模式介绍》第十七章 MVC 模式
Zend Framework 入门——快速上手
Zend Framework 入门——多国语言支持
Zend Framework 入门——错误处理
Zend Framework 入门——页面布局
详细介绍php5编程中的异常处理
PHP5 OOP编程中的代理与异常
PHP程序的常见漏洞攻击分析
PHP.MVC的模板标签系统
PHP教程:PHP编码书写规范
PHP开发大型项目的方法:OOP思想
php使用curl模拟用户登陆
php对gb编码动态转utf-8编码的几种方法评测
php设计模式介绍之章代理模式
“在phpMyAdmin使用用户口令登陆”补充
PHP入门速成

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 116 ::
收藏到网摘: n/a

有这么一段HTML,比较不规则的,如果要提取其中的链接地址和链接名称,怎么弄?

//HTML
$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://list.mp3.baidu.com/list/bangping.html" class="p14">中文金曲榜</a><br><td nowrap="nowrap">&#8226;&nbsp;<a id="top19" href="qingyinyue.html?top19" class="p14" target="_top">轻音乐</a></td>';

利用正则表达式是最简单的,其它的办法,偶米去想。。。

$pat = '/<a(.*?)href="(.*?)"(.*?)>(.*?)<\/a>/i';
preg_match_all($pat, $str, $m);

输出方法:

print_r($m[2]);
print_r($m[4]);

或者:
for($i=0;$i<count($m[2]) ;$i++ ){
    echo '<li><a href="'.$_SERVER['PHP_SELF'].'?url='.$m[2][$i].'">'.$m[4][$i].'</a>';
}

显示结果是:

Array ( [0] => http://list.mp3.baidu.com/song/A.htm?top8 [1] => http://list.mp3.baidu.com/list/bangping.html [2] => qingyinyue.html?top19 ) Array ( [0] => 歌曲列表 [1] => 中文金曲榜 [2] => 轻音乐 )

于是,我们要采集某个网站的标题及链接地址方法就出来了。。。自己套用吧。。。