laravel替换文章内容图片地址
作者:互联网
将图片下载到服务器指定目录下,将该目录挂在一个图片域名下。编辑助手函数:
<?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;
}
}
标签:laravel,dist,string,content,文章内容,match,path,替换,imgurl 来源: https://blog.csdn.net/Ty201313/article/details/122614738