ImageUrlService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Created by IntelliJ IDEA.
  4. * User: kelyliang
  5. * Date: 2024/4/10
  6. * Time: 上午 10:45
  7. */
  8. namespace App\Services\File;
  9. use App\Models\File;
  10. use DOMDocument;
  11. use Illuminate\Support\Facades\Storage;
  12. use Illuminate\Support\Str;
  13. class ImageUrlService
  14. {
  15. public function interceptImageUrl(string $comment){
  16. $newComment = null;
  17. $dom = new DOMDocument();
  18. libxml_use_internal_errors(true); // 禁用错误报告
  19. $dom->loadHTML($comment, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  20. libxml_clear_errors();
  21. // 获取所有的 img 标签
  22. $imgTags = $dom->getElementsByTagName('img');
  23. if($imgTags->length>0){
  24. // 遍历所有的 img 标签
  25. foreach ($imgTags as $imgTag) {
  26. $src = $imgTag->getAttribute('src');
  27. // 查找 &fild_ 的位置
  28. $fildPos = strpos($src, 'fild_');
  29. // 如果找到了 &fild_,则截取该位置之前的数据
  30. if ($fildPos !== false) {
  31. $src = substr($src, $fildPos); // 保留 &fild_ 及之后的部分
  32. } else {
  33. // 如果没有找到 &fild_,则清空整个 src 属性(或者根据需求处理)
  34. $src = '';
  35. }
  36. // 设置修改后的 src 属性
  37. $imgTag->setAttribute('src', $src);
  38. }
  39. $newComment = $dom->saveHTML();
  40. }
  41. return $newComment??$comment;
  42. }
  43. public function getImageUrl(string $comment){
  44. $newComment = null;
  45. preg_match_all('/<img\s+[^>]*src=[\'"]([^\'"]*)[\'"][^>]*>/i', $comment, $matches);
  46. $ids = [];
  47. // 遍历匹配到的 src 属性值
  48. foreach ($matches[1] as $src) {
  49. // 使用正则表达式从 src 属性值中提取 fild_ 后面的 ID
  50. if (preg_match('/fild_(\d+)/', $src, $idMatch)) {
  51. $ids[] = $idMatch[1]; // 将提取到的 ID 添加到数组中
  52. }
  53. }
  54. if(!empty($ids)){
  55. $files=File::query()->whereIn('id',$ids)->get();
  56. $search = [];
  57. $replace = [];
  58. foreach ($files as $file){
  59. $url=Storage::url($file->pathname);
  60. $placeholder = "fild_" . $file->id; // 生成占位符
  61. $search[] = $placeholder; // 将占位符添加到 $search 数组
  62. $replace[] = $url."&fild_".$file->id; // 将替换 URL 添加到 $replace 数组
  63. }
  64. $newComment=Str::replace($search, $replace, $comment);
  65. }
  66. return $newComment??$comment;
  67. }
  68. }