php 正则 抓取网页( php正则学了抓取特定标签具有特定属性值的接口通用)
优采云 发布时间: 2022-03-15 12:02php 正则 抓取网页(
php正则学了抓取特定标签具有特定属性值的接口通用)
如何使用 PHP 正则表达式获取标签的特定属性值
学了几天php正则,抓到了网站的一些数据,所以发现每次都要重新写正则很麻烦,所以想写个通用的接口,用特定的抓取特定的标签属性值。代码。
//$html-被查找的字符串 $tag-被查找的标签 $attr-被查找的属性名 $value-被查找的属性值
function get_tag_data($html,$tag,$attr,$value){
$regex = "/(.*?)/is";
echo $regex."
";
preg_match_all($regex,$html,$matches,PREG_PATTERN_ORDER);
return $matches[1];
}
//返回值为数组 查找到的标签内的内容
这里只是一个例子
header("Content-type: text/html; charset=utf-8");
$temp = '
';
$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正则表达式捕获标签具体属性值的方法。我希望它对你有帮助。如有任何问题,请给我留言,小编会及时回复您。. 非常感谢您对来客网网站的支持!