laravel替换文章内容图片地址

本文介绍了如何在Laravel中实现将文章内的图片地址替换为CDN链接,通过下载图片到服务器指定目录,挂载到图片域名下,辅助以自定义编辑助手函数来完成这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将图片下载到服务器指定目录下,将该目录挂在一个图片域名下。编辑助手函数:

<?php

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

if (!function_exists('replaceImageUrl')) {
    /**
     * 替换文章内容图片地址
     * @param string $content
     * @return string
     */
    function replaceImageUrl(string $content): string
    {
        //保存路径
        $path =  'image/' . Date('Y-m-d') . "/assets/news/";
        $dist = 'app/iptv-webservice/' .$path;
        $host = env('HTTP');// 例:https://haha.xixi.org/image/
        if (!File::exists(storage_path($dist))) {
            File::makeDirectory(storage_path($dist), 0755, true, true);
        }
        preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $content, $match);
        foreach($match[1] as $imgurl){
            $img=file_get_contents($imgurl);
            if(!empty($img)) {
                $filename = explode('.', $imgurl);
                $tmpFilename = $filename;
                $imageType = array_pop($tmpFilename);
                $tmpImage = implode('.', $tmpFilename);
                $relativePathToFile = $path.md5($tmpImage).'.'.$imageType;
                Storage::put($relativePathToFile, Image::make($imgurl)->encode($imageType));
                $savePath = $host . $relativePathToFile;
                $content = str_replace($imgurl,$savePath,$content);
            }
        }
        return $content;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值