ImageUrlService.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. $newComment = null;
  49. preg_match_all('/<img\s+[^>]*src=[\'"]([^\'"]*)[\'"][^>]*>/i', $comment, $matches);
  50. $ids = [];
  51. // 遍历匹配到的 src 属性值
  52. foreach ($matches[1] as $src) {
  53. // 使用正则表达式从 src 属性值中提取 fild_ 后面的 ID
  54. if (preg_match('/fild_(\d+)/', $src, $idMatch)) {
  55. $ids[] = $idMatch[1]; // 将提取到的 ID 添加到数组中
  56. }
  57. }
  58. if(!empty($ids)){
  59. $files=File::query()->whereIn('id',$ids)->get();
  60. $search = [];
  61. $replace = [];
  62. foreach ($files as $file){
  63. $url=Storage::url($file->pathname);
  64. $placeholder = "fild_" . $file->id; // 生成占位符
  65. $search[] = $placeholder; // 将占位符添加到 $search 数组
  66. $replace[] = $url."&fild_".$file->id; // 将替换 URL 添加到 $replace 数组
  67. }
  68. $newComment=Str::replace($search, $replace, $comment);
  69. }
  70. return $newComment??$comment;
  71. }
  72. }