php正则如何替换src?

本篇内容主要讲解“php正则如何替换src”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php正则如何替换src”吧!

php正则替换src的方法:1、打开相应的PHP文件;2、通过“if(!function_exists('get_img_path')){function get_img_path($img){...}”方法实现根据不同环境获取图片路径;3、通过“htmlspecialchars_decode”方法在页面中显示富文本编辑器内容即可。

php 正则怎么替换src?

PHP-正则匹配文章图片标签src的内容并替换

后端富文本编辑器中编辑的图片在各种端中显示

由于不在同一服务器,图片访问路劲不同

这个时候需要批量匹配并替换

//$info->content 是接口中返回文章的内容
    $preg = '#<img(.+?)src\s*=\s*[\"|\']([^"|^\']+?)[\"|\']([^>]*?)>#';
        $info->content = preg_replace_callback($preg,function ($matches){
            $replace = get_img_path($matches[2]);//要替换的src
            return "<img{$matches[1]}src=\"$replace\"{$matches[3]}>";
        }, $info->content);

get_img_path()函数根据不同环境获取图片路径

if(!function_exists('get_img_path')){
    function get_img_path($img){
        //当前环境
        $env_info  = getenv('APP_ENV');
        switch ($env_info){
            case 'local':
                $url = 'https://local.***.com/'.$img;
                break;
            case 'test':
                $url = 'https://test.***.com/'.$img;
                break;
            case 'production':
                $url = 'https://production.***.com/'.$img;
                break;
            default:
                $url = 'https://local.***.com/'.$img;
                break;
        }
        return $url;
    }
}

在页面中显示富文本编辑器内容

 <?php echo htmlspecialchars_decode($info->content);?>

到此,相信大家对“php正则如何替换src”有了更深的了解,不妨来实际操作一番吧!这里是***网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!