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){ if (! $comment) { return $comment; } $newComment = null; preg_match_all('/]*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; } }