From ec8f1f0589e33bef7aab7038940ec7c52dfb36d3 Mon Sep 17 00:00:00 2001 From: FrankZamora Date: Thu, 27 Nov 2025 13:31:11 -0600 Subject: [PATCH] fix(youtube-facade): improve regex pattern for iframe detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Made regex more flexible to handle various attribute orders - Added quick check before regex processing - Added null check for preg_replace_callback result - Supports both single and double quotes in src attribute 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- .../Services/YoutubeFacadeContentFilter.php | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/Public/YoutubeFacade/Infrastructure/Services/YoutubeFacadeContentFilter.php b/Public/YoutubeFacade/Infrastructure/Services/YoutubeFacadeContentFilter.php index 32f8b759..915a72aa 100644 --- a/Public/YoutubeFacade/Infrastructure/Services/YoutubeFacadeContentFilter.php +++ b/Public/YoutubeFacade/Infrastructure/Services/YoutubeFacadeContentFilter.php @@ -32,23 +32,26 @@ final class YoutubeFacadeContentFilter */ public function filter(string $content): string { - // Match YouTube iframes (with or without video-wrapper) - // Pattern handles both youtube.com/embed/ and youtube-nocookie.com/embed/ - $pattern = '/
\s*]*src="https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]+)[^"]*"[^>]*><\/iframe>\s*<\/div>/is'; + // Check if content has YouTube embeds at all (quick check) + if (strpos($content, 'youtube.com/embed/') === false && strpos($content, 'youtube-nocookie.com/embed/') === false) { + return $content; + } - $content = preg_replace_callback($pattern, function ($matches) { + // Pattern to match YouTube iframes + // Handles: youtube.com/embed/ and youtube-nocookie.com/embed/ + // More flexible: allows any attributes in any order, whitespace variations + $pattern = '/]*src=["\']https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]+)[^"\']*["\'][^>]*>\s*<\/iframe>/is'; + + $result = preg_replace_callback($pattern, function ($matches) { $videoId = $matches[1]; return $this->renderer->render($videoId); }, $content); - // Also match standalone iframes without wrapper - $patternStandalone = '/]*src="https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]+)[^"]*"[^>]*><\/iframe>/is'; + // Return original content if regex failed + if ($result === null) { + return $content; + } - $content = preg_replace_callback($patternStandalone, function ($matches) { - $videoId = $matches[1]; - return $this->renderer->render($videoId); - }, $content); - - return $content; + return $result; } }