fix(youtube-facade): improve regex pattern for iframe detection

- 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 <noreply@anthropic.com>
This commit is contained in:
FrankZamora
2025-11-27 13:31:11 -06:00
parent 133b364c78
commit ec8f1f0589

View File

@@ -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 = '/<div class="video-wrapper">\s*<iframe[^>]*src="https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]+)[^"]*"[^>]*><\/iframe>\s*<\/div>/is';
$content = preg_replace_callback($pattern, function ($matches) {
$videoId = $matches[1];
return $this->renderer->render($videoId);
}, $content);
// Also match standalone iframes without wrapper
$patternStandalone = '/<iframe[^>]*src="https?:\/\/(?:www\.)?(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]+)[^"]*"[^>]*><\/iframe>/is';
$content = preg_replace_callback($patternStandalone, function ($matches) {
$videoId = $matches[1];
return $this->renderer->render($videoId);
}, $content);
// 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;
}
// 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 = '/<iframe\s+[^>]*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);
// Return original content if regex failed
if ($result === null) {
return $content;
}
return $result;
}
}