<?php
header("Content-type:text/html;charset=utf-8");
$str = ‘asdfasdfasdf<img src="http://192.168.7.182:8083/File/upload/2015/0109/14/54af75cebaa20.jpg" >ffggfsdasdfasdfasdfasdfasdfsadfasdf<img src="http://192.168.7.182:8083/File/upload/2015/0109/14/54af77d61f9ed.jpg" >‘;
preg_match_all(‘<img src="(.*?)">‘,$str, $bodyarr);//正则匹配找到图片的src地址
foreach($bodyarr[1] as $key=>$val){//多图片src循环
$fileinfo = getimagesize($val);//传入src路径,获取图片信息,函数具体意思看php手册
if($fileinfo[0] > 400){//判断宽度是否大于400
$letters = array(‘/‘, ‘.‘);
$fruit = array(‘\/‘, ‘\.‘);
$output = str_replace($letters, $fruit, $val);//为了方便正则替换时可以识别到唯一的图片,对图片src进行正则形式的转码
$patterns[$key] = ‘/<img src="‘.$output.‘"/‘;
$replacements[$key] = ‘<img src="‘.$val.‘" width="400"‘;
}
}
if($patterns && $replacements)//判断是否有图片需要替换
$str = preg_replace($patterns, $replacements, $str);//执行替换,对$str变量进行重新赋值
echo $str;
?>
本文出自 “php工程师的博客” 博客,请务必保留此出处http://340411305.blog.51cto.com/7627178/1601161
原文地址:http://340411305.blog.51cto.com/7627178/1601161