php中html页面提取图片路径并替换的方法
发布时间:2015-12-11 编辑:jiaochengji.com
为大家介绍php代码从html页面中提取出图片路径,并进行内容替换的方法,有需要的朋友,可以参考下。
代码如下:
复制代码 代码示例:
<?php
/**
* php 提取html中图片并替换
* autho www.jbxue.com
*/
//要替换的内容
$content = '<img alt="" src="js/fckeditor/UserFiles/image/F201005201210502415831196.jpg" width="600" height="366"><br><br><br><br><img alt="" src="js/fckeditor/UserFiles/image/33_avatar_middle.jpg" width="120" height="120">';
//提取图片路径的src的正则表达式
preg_match_all("/<img(.*)src="([^"]+)"[^>]+>/isU",$content,$matches);
$img = "";
if(!emptyempty($matches)) {
//注意,上面的正则表达式说明src的值是放在数组的第三个中
$img = $matches[2];
}else {
$img = "";
}
if (!emptyempty($img)) {
$img_url = "http://".$_SERVER['SERVER_NAME'];
$patterns= array();
$replacements = array();
foreach($img as $imgItem){
$final_imgUrl = $img_url.$imgItem;
$replacements[] = $final_imgUrl;
$img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
$patterns[] = $img_new;
}
//让数组按照key来排序
ksort($patterns);
ksort($replacements);
//替换内容
$vote_content = preg_replace($patterns, $replacements, $content);
?>
/**
* php 提取html中图片并替换
* autho www.jbxue.com
*/
//要替换的内容
$content = '<img alt="" src="js/fckeditor/UserFiles/image/F201005201210502415831196.jpg" width="600" height="366"><br><br><br><br><img alt="" src="js/fckeditor/UserFiles/image/33_avatar_middle.jpg" width="120" height="120">';
//提取图片路径的src的正则表达式
preg_match_all("/<img(.*)src="([^"]+)"[^>]+>/isU",$content,$matches);
$img = "";
if(!emptyempty($matches)) {
//注意,上面的正则表达式说明src的值是放在数组的第三个中
$img = $matches[2];
}else {
$img = "";
}
if (!emptyempty($img)) {
$img_url = "http://".$_SERVER['SERVER_NAME'];
$patterns= array();
$replacements = array();
foreach($img as $imgItem){
$final_imgUrl = $img_url.$imgItem;
$replacements[] = $final_imgUrl;
$img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
$patterns[] = $img_new;
}
//让数组按照key来排序
ksort($patterns);
ksort($replacements);
//替换内容
$vote_content = preg_replace($patterns, $replacements, $content);
?>
大家也可以参考下php正则取图片路径与php取图片路径的正则写法,里面有关于用正则取内容中图片的方法,对理解以上的代码,会有所帮助的。
您可能感兴趣的文章:
php中html页面提取图片路径并替换的方法
php正则匹配重写html图片img路径的代码一例
ASP.NET MasterPage中图片路径的解决办法
php匹配图片地址的代码一例
将网页导出为Word文档的php代码介绍
php 获取文章内容的第一张图片示例
php多图上传怎么保存路径
php可以把页面转化成图片吗
用PHP实现一个简易版文件上传功能(超详细讲解)
PHP正则提取或替换img标记属性的实例代码
[关闭]