Home >Backend Development >PHP Problem >How to modify pictures in php html

How to modify pictures in php html

藏色散人
藏色散人Original
2021-03-03 10:12:391862browse

php html修改图片的方法:首先创建一个PHP示例文件;然后通过PHP正则提取html图片img标记中的任意属性;最后通过正则表达式修改替换图片指定属性即可。

How to modify pictures in php html

本文操作环境:windows7系统、PHP7.1版,DELL G3电脑。

php正则提取html图片(img)src地址与任意属性

简单版:

  <?php  
    header("Content-Type: text/html;charset=utf-8");  
      
    $str = &#39;<div class="ui-block-a" align="center">  
            <a href="online-39.html"><img class="lazy" width="131" height="177" src="http://www.smsyun.com/uploads/image/20140620/2014052010425.jpg"/>  
            <h3>2014年</h3></a>  
          </div>&#39;;  
      
    $imgpreg = "/<img (.*?) src=\"(.+?)\".*?>/";  
    preg_match($imgpreg,$str,$img);  
    $mycount=count($img)-1;  
     $imgval = $iim[$mycount];  
    if(!empty($imgval)){  
        echo $imgval;  
    }else{  
        echo &#39;no&#39;;  
    }  
    ?>

详细版:

    <?php  
    /*PHP正则提取图片img标记中的任意属性*/  
    $str = &#39;<center><img src="/uploads/images/20100516000.jpg" height="120" width="120"><br />PHP正则提取或更改图片img标记中的任意属性</center>&#39;;  
      
    //1、取整个图片代码  
    preg_match(&#39;/<\s*img\s+[^>]*?src\s*=\s*(\&#39;|\")(.*?)\\1[^>]*?\/?\s*>/i&#39;,$str,$match);  
    echo $match[0];  
      
    //2、取width  
    preg_match(&#39;/<img.+(width=\"?\d*\"?).+>/i&#39;,$str,$match);  
    echo $match[1];  
      
    //3、取height  
    preg_match(&#39;/<img.+(height=\"?\d*\"?).+>/i&#39;,$str,$match);  
    echo $match[1];  
      
    //4、取src  
    preg_match(&#39;/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i&#39;,$str,$match);  
    echo $match[1];  
      
    /*PHP正则替换图片img标记中的任意属性*/  
    //1、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg")  
    print preg_replace(&#39;/(<img.+src=\"?.+)(images\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/i&#39;,"\${1}uc/images/\${3}",$str);  
    echo "<hr/>";  
      
    //2、将src="/uploads/images/20100516000.jpg"替换为src="/uploads/uc/images/20100516000.jpg",并省去宽和高  
    print preg_replace(&#39;/(<img).+(src=\"?.+)images\/(.+\.(jpg|gif|bmp|bnp|png)\"?).+>/i&#39;,"\${1} \${2}uc/images/\${3}>",$str);  
    ?>

【推荐学习:PHP视频教程

The above is the detailed content of How to modify pictures in php html. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn