headers->get('Content-Type') === 'text/html; charset=UTF-8') { $content = $response->getContent(); // 儲存提取出的樣式內容 $styles = []; $styleCounter = 0; // 第一步:處理內聯樣式,將 style 轉換為 class $content = preg_replace_callback( '/<([a-z][a-z0-9]*)\b([^>]*)style=["\']([^"\']+)["\']([^>]*)>/i', function ($matches) use (&$styles, &$styleCounter) { $tag = $matches[1]; // 標籤名稱,例如 div $beforeAttrs = trim($matches[2]); // style 前的屬性 $styleContent = $matches[3]; // 內聯樣式內容 $afterAttrs = trim($matches[4]); // style 後的屬性 // 生成唯一的 class 名稱 $className = 'inline-style-' . $styleCounter++; $styles[$className] = $styleContent; // 組合新的標籤,保留其他屬性並添加 class $newAttrs = $beforeAttrs . ($beforeAttrs ? ' ' : '') . 'class="' . $className . '"' . ($afterAttrs ? ' ' : '') . $afterAttrs; return '<' . $tag . ' ' . trim($newAttrs) . '>'; }, $content ); // 第二步:為