新增:使用正则替换内容中的图片路径公共方法

This commit is contained in:
2026-08-06 15:47:46 +08:00
parent 64aec80889
commit ff7adab00d

View File

@@ -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('/<img([^>]*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 '<img' . $prefix . $newSrc . $suffix . '>';
}, $content);
return [$content, $filePath];
}
}