From ff7adab00d7a99b03de0af1e9c7c10b7d8764371 Mon Sep 17 00:00:00 2001 From: zj Date: Thu, 6 Aug 2026 15:47:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=EF=BC=9A=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E6=AD=A3=E5=88=99=E6=9B=BF=E6=8D=A2=E5=86=85=E5=AE=B9=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=E5=9B=BE=E7=89=87=E8=B7=AF=E5=BE=84=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Library/Util.php | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/Library/Util.php b/src/Library/Util.php index 2d58577..33f25af 100644 --- a/src/Library/Util.php +++ b/src/Library/Util.php @@ -340,6 +340,9 @@ final class Util /** * 移除内容中图片的文件域名 + * @param string|array $content 内容 + * @param string|null $fileDomain 文件域名 + * @return array|string */ public static function removeFileDomain(array|string $content, ?string $fileDomain = null): array|string { @@ -349,4 +352,39 @@ final class Util $fileDomain = $fileDomain ?? self::getFileDomainFromNacos() . '/'; return str_replace($fileDomain, '', $content); } + + /** + * 使用正则替换内容中的图片路径 + * @param array|string $content 内容 + * @param string|null $oldDomain 旧域名 + * @param string $search 搜索字符串 + * @param string $replace 替换字符串 + * @return array|string + */ + public static function replaceImgDomainPreg(array|string $content, ?string $oldDomain, string $search = '', string $replace = ''): array + { + if (empty($content)) { + return $content; + } + $content = self::removeFileDomain($content, $oldDomain); + $filePath = []; + $content = preg_replace_callback('/]*src\s*=\s*["\'])([^"\']*)(["\'][^>]*)>/i', function ($matches) use ($search, $replace, &$filePath) { + $prefix = $matches[1]; + $src = $matches[2]; + $suffix = $matches[3]; + + if (!empty($search)) { + $newSrc = str_replace($search, $replace, $src); + } else { + $newSrc = $src; + } + $filePath[] = [ + 'old' => $src, + 'new' => $newSrc + ]; + return ''; + }, $content); + + return [$content, $filePath]; + } }