您好,欢迎来到美希科技。
搜索
您的当前位置:首页php如何实现html内容替换

php如何实现html内容替换

来源:美希科技


推荐:《PHP视频教程》

  • 本方法适用于任何品牌的电脑。

  • php修改html里面的内容

    已知下面一段html

    $a="<p><img src=\"/upload/store/1/ue/image/15682821258332.png\" title=\"15682821258332.png\" alt=\"1.png\"/><img src=\"http://dimg04.c-ctrip.com/images/300q12000000rq2t956CB.jpg\" alt=\"undefined\"/><img src=\"https://dimg04.c-ctrip.com/images/300m12000000sdsca92E2.jpg\"/><img src=\"https://dimg04.c-ctrip.com/images/300w12000000rutmrD6CB.jpg\" alt=\"undefined\"/><img src=\"https://dimg04.c-ctrip.com/images/300u12000000rorex415F.jpg\" alt=\"undefined\"/><img src=\"http://dimg04.c-ctrip.com/images/300k12000000rsyxgBA05.jpg\" alt=\"undefined\"/></p>"

    里面有http和https还有本地相对路径的url

    普遍用法:

    $pattern="/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
    preg_match_all($pattern,htmlspecialchars_decode($a),$match);
    if(!empty($match[1])){
     print_r($match[1]);
    }else{
    echo "没得";
    }

    先匹配所有在循环$match[1]

    循环之后foreach($match[1] as $val){preg_replace('#src="'.$val.'"/#is', 'src="aaaaa/',$a);}

    这样我觉得挺麻烦的

    升级用法:

    $host="http://mp.csdn.net"
    $newContent = preg_replace_callback("/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", function($m) use($host){
    
     if(strpos($m[1],'http://') || strpos($m[1],'https://')){
     return $m[0];
     }else{
     $img=preg_replace('#src="/#is', 'src="'.$host.'/',$m[0]);
     return $img;
     }
    }, $a);

    这个方法虽然用得少但是批处理的时候看效果超级好哟!

    这种闭包函数我个人挺喜欢的。代码阅读性很高

    Copyright © 2019- mxzg.net 版权所有

    违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

    本站由北京市万商天勤律师事务所王兴未律师提供法律服务