How can PHP regex patterns be used effectively to extract and display YouTube videos in forum posts?
To extract and display YouTube videos in forum posts using PHP regex patterns, you can search for the YouTube video URL within the post content and then extract the video ID from the URL. Once you have the video ID, you can embed the video using the YouTube embed code.
// Sample forum post content
$post_content = "Check out this awesome YouTube video: https://www.youtube.com/watch?v=ABC123";
// Define the regex pattern to match YouTube video URLs
$pattern = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/';
// Search for YouTube video URL in the post content
if (preg_match($pattern, $post_content, $matches)) {
$video_id = $matches[1];
// Embed the YouTube video using the video ID
$embed_code = '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $video_id . '" frameborder="0" allowfullscreen></iframe>';
// Display the embedded video
echo $embed_code;
}