php正则匹配文章中的远程图片地址并下载图片至本地

  • 后端
  • 2022-03-23
  • 1069 已阅读
  • 作者: huwhois
  • 来源: 网络
简介Ueditor 1.4.3 版本在默认 config 中没了保存文章中的远程图片到本地的配置, 百度出来的改配置都没成功. 也就只能自己后台处理提交的文章内容了, 主要思路为PHP正则匹配出非本地图片路径, 然后图片再保存在本地服务器上, 然后逐一文章中的图片路径.

Ueditor 1.4.3 版本在默认 config 中没了保存文章中的远程图片到本地的配置, 百度出来的改配置都没成功. 也就只能自己后台处理提交的文章内容了, 主要思路为PHP正则匹配出非本地图片路径, 然后图片再保存在本地服务器上, 然后逐一文章中的图片路径.


1.  正则匹配图片路径

    // 去除反斜杠
    $content = stripslashes ($content);
    $img_array = [];
    // 匹配所有远程图片
    $pattern = '/src="(http[s]://.*)"/isU';
    preg_match_all ($pattern,$content,$img_array);
    // 删除重复 url
    $img_arrays = array_unique ($img_array[1]);
    var_dump($img_arrays)
    exit;


2. 保存远程图片到本地

function urlImg($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_NOBODY, 0); // 只取body头
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $package = curl_exec($ch);
    $httpinfo = curl_getinfo($ch);
    curl_close($ch);
    $imageAll = array_merge(array(
        'imgBody' => $package
    ), $httpinfo);
    if ($httpinfo['download_content_length'] > 4 * 1024 * 1024) {
        throw new Exception("文件太大", 1);
    }
    $type = null;
    switch ($imageAll['content_type']) {
        case 'image/gif':
            $type = "gif";
            break;
        case 'image/webp':
            $type = "webp";
            break;
        case 'image/jpeg':
            $type = "jpg";
            break;
        case 'image/png':
            $type = "png";
            break;
        default:
            $type = null;
            break;
    }

    if (!$type) {
        throw new Exception("不支持的文件后缀", 1);
    }

    // 文件保存目录路径(请更换为你自己的路径, 你可以var_dump一下)
    $save_path = realpath($_SERVER ['DOCUMENT_ROOT'] . 'upload') . '/' . date ( "Ymd" );
    $imgName = generate_stochastic_string(12);   /* 生成随机字符串 详情见(http://www.huwhois.cn/index/2019/04-08/5.html) */ 
    if (!file_exists($save_path )) {
        mkdir($temp, 0755, true);
    }
    $filename= $save_path . $imgName . $type;
    file_put_contents($filename, $imageAll["imgBody"]);
    return filename;
}


3. 替换文章中的远程图片链接

function saveRomteImage($content)
{
    $content = stripslashes($content);
    $img_array = [];
    // 匹配所有远程图片
    $pattern = '/src="(http[s]://.*)"/isU';
    preg_match_all($pattern, $content, $img_array);
    // 删除重复 url
    $img_arrays = array_unique($img_array[1]);
    foreach ($img_arrays as $value) {
        $filename = urlImg($value);
        // dump($filename);
        $content = str_replace($value, $filename, $content);
    }
    return $content;
}


很赞哦! ( 1 )