ImageUrlService.php 2.7 KB

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