123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- /**
- * Created by IntelliJ IDEA.
- * User: kelyliang
- * Date: 2024/4/10
- * Time: 上午 10:45
- */
- namespace App\Services\File;
- use App\Models\File;
- use DOMDocument;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- class ImageUrlService
- {
- public function interceptImageUrl(string $comment){
- $newComment = null;
- $dom = new DOMDocument();
- libxml_use_internal_errors(true); // 禁用错误报告
- $dom->loadHTML($comment, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
- libxml_clear_errors();
- // 获取所有的 img 标签
- $imgTags = $dom->getElementsByTagName('img');
- if($imgTags->length>0){
- // 遍历所有的 img 标签
- foreach ($imgTags as $imgTag) {
- $src = $imgTag->getAttribute('src');
- // 查找 &fild_ 的位置
- $fildPos = strpos($src, 'fild_');
- // 如果找到了 &fild_,则截取该位置之前的数据
- if ($fildPos !== false) {
- $src = substr($src, $fildPos); // 保留 &fild_ 及之后的部分
- } else {
- // 如果没有找到 &fild_,则清空整个 src 属性(或者根据需求处理)
- $src = '';
- }
- // 设置修改后的 src 属性
- $imgTag->setAttribute('src', $src);
- }
- $newComment = $dom->saveHTML();
- }
- return $newComment??$comment;
- }
- public function getImageUrl(string $comment){
- $newComment = null;
- preg_match_all('/<img\s+[^>]*src=[\'"]([^\'"]*)[\'"][^>]*>/i', $comment, $matches);
- $ids = [];
- // 遍历匹配到的 src 属性值
- foreach ($matches[1] as $src) {
- // 使用正则表达式从 src 属性值中提取 fild_ 后面的 ID
- if (preg_match('/fild_(\d+)/', $src, $idMatch)) {
- $ids[] = $idMatch[1]; // 将提取到的 ID 添加到数组中
- }
- }
- if(!empty($ids)){
- $files=File::query()->whereIn('id',$ids)->get();
- $search = [];
- $replace = [];
- foreach ($files as $file){
- $url=Storage::url($file->pathname);
- $placeholder = "fild_" . $file->id; // 生成占位符
- $search[] = $placeholder; // 将占位符添加到 $search 数组
- $replace[] = $url."&fild_".$file->id; // 将替换 URL 添加到 $replace 数组
- }
- $newComment=Str::replace($search, $replace, $comment);
- }
- return $newComment??$comment;
- }
- }
|