返回PHP正则表达......登陆

PHP正则表达式抓取某个标签的特定属性值的方法

巴扎黑2016-12-28 10:43:35393

这篇文章主要介绍了PHP正则表达式抓取某个标签的特定属性值的方法的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下.

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

1

2

3

4

5

6

7

8

//$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];

}

//返回值为数组 查找到的标签内的内容

下面随便给出一个例子

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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

输出结果为

1

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

查看源码可以看到

1

2

3

4

5

6

7

8

9

10

11

12

13

14

array(6) {

[0]=>

string(6) "首页"

[1]=>

string(6) "日志"

[2]=>

string(6) "LOFTER"

[3]=>

string(6) "相册"

[4]=>

string(6) "博友"

[5]=>

string(9) "关于我"

}

更多关于PHP正则表达式抓取某个标签的特定属性值的方法请关注PHP中文网(www.php.cn)其它文章!

最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送