PHP 正则表达式截取HTML



用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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值