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

PHP
关于时间计算的结总
一些PHP写的小东西
用缓存实现静态页面的测试
PHP数字格式化
echo, print, printf 和 sprintf 区别
让你的网站首页自动选择语言转跳
如何使用PHP往windows中添加用户
PHP产生随机字符串函数
同一空间绑定多个域名而实现访问不同页面的PHP代码
实现 win2003 下 mysql 数据库每天自动备份
eWebEditor v3.8 商业完整版 (PHP)
PHP中,文件上传
計算你開發的 PHP 程式大小
產生圖片隨機字串
数字转英文
ajax缓存问题解决途径
PHP字符函数大全
从网上搜到的phpwind 0day的代码
IIS下配置Php+Mysql+zend的图文教程
如何写php程序?

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 224 ::
收藏到网摘: 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] => 轻音乐 )

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