怎么用PHP正则表达式抓取某个标签的特定属性值

发布时间:2021-08-12 13:49:14 作者:chen
来源:亿速云 阅读:136

这篇文章主要介绍“怎么用PHP正则表达式抓取某个标签的特定属性值”,在日常操作中,相信很多人在怎么用PHP正则表达式抓取某个标签的特定属性值问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么用PHP正则表达式抓取某个标签的特定属性值”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

php正则学了一些日子,抓了一些网站的数据,从而发现每次都自己写正则重新抓很麻烦,于是就想写一个抓取特定标签具有特定属性值的接口通用,直接上代码。

//$html-被查找的字符串 $tag-被查找的标签 $attr-被查找的属性名 $value-被查找的属性值
function get_tag_data($html,$tag,$attr,$value){
$regex = "/<$tag.*?$attr=\".*?$value.*?\".*?>(.*?)<\/$tag>/is";
echo $regex."<br>";
preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
return $matches[1];
}
//返回值为数组 查找到的标签内的内容

下面随便给出一个例子

header("Content-type: text/html; charset=utf-8");
$temp = '<ul class="noul clearfix">
<li class="w w0">
<a class="i i0 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/">首页</a>
</li>
<li class="w w1 selected">
<a class="i i1 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/blog/">日志</a>
</li>
<li class="w w9">
<a class="i i9 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/loftarchive/">LOFTER</a>
</li>
<li class="w w2">
<a class="i i2 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/album/">相册</a>
</li>
<li class="w w5">
<a class="i i5 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/friends/">博友</a>
</li>
<li class="w w6">
<a class="i i6 fc01 h" hidefocus="true" href="http://phpway.blog.163.com/profile/">关于我</a>
</li>
</ul>';
$result = get_tag_data($temp,"a","class","fc01");
var_dump($result);

输出结果为

array(6) { [0]=> string(6) "首页" [1]=> string(6) "日志" [2]=> string(6) "LOFTER" [3]=> string(6) "相册" [4]=> string(6) "博友" [5]=> string(9) "关于我" }

查看源码可以看到

array(6) {
[0]=>
string(6) "首页"
[1]=>
string(6) "日志"
[2]=>
string(6) "LOFTER"
[3]=>
string(6) "相册"
[4]=>
string(6) "博友"
[5]=>
string(9) "关于我"
}

到此,关于“怎么用PHP正则表达式抓取某个标签的特定属性值”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. PHP利用正则表达式替换标签
  2. 关于用php的curl批量抓取内容

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:Python如何确定多项式拟合/回归的阶数

下一篇:python中内置模块的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》