263 || !preg_match('~^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?::[0-9]{1,5})?$~iD', $value))) { throw new RuntimeException('请填写 HTTPS CDN 源站地址,例如 https://cdn.example.com。'); } if (($port = parse_url($value, PHP_URL_PORT)) !== null && ($port === false || $port < 1)) { throw new RuntimeException('CDN 端口无效。'); } return $value; } public static function url(string $path, string $cdn): string { return str_starts_with($path, '/assets/') ? $cdn . $path : $path; } public static function rewrite(string $html, string $cdn): string { if ($cdn === '') { return $html; } // Match opening tags separately from comments and text-only elements' contents. $tags = <<<'REGEX' ~|\z)|(?<(?:(?script|style|textarea|title)|[a-z][\w:-]*)(?=[\s/>])(?:[^<>"']++|"[^"]*"|'[^']*')*+>)(?(textTag)(?.*?(?:\s*>|\z)))~is REGEX; $attributes = <<<'REGEX' ~(\s+)([^\s/<>="']+)(?:(\s*=\s*)("[^"]*"|'[^']*'|[^\s<>"'=`]+))?~ REGEX; return preg_replace_callback($tags, static function (array $tag) use ($attributes, $cdn): string { if (!isset($tag['opening'])) { return $tag[0]; } $opening = preg_replace_callback($attributes, static function (array $attribute) use ($cdn): string { if (!isset($attribute[4]) || !in_array(strtolower($attribute[2]), ['src', 'href', 'poster'], true)) { return $attribute[0]; } $value = $attribute[4]; $quote = str_starts_with($value, '"') || str_starts_with($value, "'") ? $value[0] : ''; $path = $quote === '' ? $value : substr($value, 1, -1); return $attribute[1] . $attribute[2] . $attribute[3] . $quote . self::url($path, $cdn) . $quote; }, $tag['opening']) ?? $tag['opening']; return $opening . ($tag['tail'] ?? ''); }, $html) ?? $html; } }