博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP正则表达式提取html超链接中的href地址
阅读量:4624 次
发布时间:2019-06-09

本文共 1055 字,大约阅读时间需要 3 分钟。

用php的正则表达式相关函数,实现提取html超链接<a href="地址"></a>中的地址

 

<?php

$preg='/<a .*?href="(.*?)".*?>/is';

$str ='<a href="链接1">URLNAME</a>文本段1<a href="链接2" target="_blank">URLNAME</a>文本段2<a  target="_blank" href="链接3">URLNAME</a>...文本段n';

preg_match_all($preg,$str,$match);//在$str中搜索匹配所有符合$preg加入$match中

for($i=0;$i<count($match[1]);$i++)//逐个输出超链接地址

{

  echo $match[1][$i]."<br />";

}

?>

 

最终输出:

链接1<br />链接2<br />链接3<br />

 

 

附一个

PHP的正则表达式提取图片地址的代码。

 

$str='<p style="padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 200%;"><img border="0" src="upfiles/2009/07/1246430143_4.jpg" alt=""/></p><p style="padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 200%;"><img border="0" src="upfiles/2009/07/1246430143_3.jpg" alt=""/></p><p style="padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 200%;"><img border="0" src="upfiles/2009/07/1246430143_1.jpg" alt=""/></p>'; 

$pattern="/<[img|IMG].*?src=['|"](.*?(?:[.gif|.jpg]))['|"].*?[/]?>/"; 

preg_match_all($pattern,$str,$match); 

print_r($match);

转载于:https://www.cnblogs.com/zxidong/p/6407305.html

你可能感兴趣的文章
leetcode笔记:Pascal&#39;s Triangle
查看>>
ASP.NET性能优化之构建自定义文件缓存
查看>>
Shell——windows上写完放入linux的时候需要注意的问题
查看>>
65条常用的正则表达式
查看>>
Vscode断点调试PHP
查看>>
做前端要做的6大事
查看>>
LeetCode 813. Largest Sum of Averages
查看>>
vSphere、Hyper-V与XenServer 你选哪个?
查看>>
java.lang.UnsupportedClassVersionError
查看>>
实现接口必须要加注解@Override吗
查看>>
apicloud UISearchBar 使用方法
查看>>
【spring+websocket的使用】
查看>>
mongo二维数组操作
查看>>
localStorage之本地储存
查看>>
Archlinux 交换左Ctrl和Cap键
查看>>
#openstack故障处理汇总
查看>>
搜索旋转排序数组 II
查看>>
20、docker swarm
查看>>
psp工具软件前景与范围文档
查看>>
day06-三元表达式
查看>>