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]; + } }