How can PHP code be used to automatically convert YouTube video URLs into embeddable iframe codes in user profiles?

To automatically convert YouTube video URLs into embeddable iframe codes in user profiles, we can use PHP to parse the URL, extract the video ID, and then generate the corresponding iframe code. This can be achieved by using regular expressions to match the YouTube URL pattern and extract the video ID from it. Once we have the video ID, we can construct the iframe code with the ID embedded within it.

<?php
function convertYouTubeURLtoEmbed($url) {
    $pattern = '/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/';
    preg_match($pattern, $url, $matches);
    
    if(isset($matches[1])) {
        $videoID = $matches[1];
        $embedCode = '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $videoID . '" frameborder="0" allowfullscreen></iframe>';
        return $embedCode;
    } else {
        return 'Invalid YouTube URL';
    }
}

// Example usage
$userYouTubeURL = 'https://www.youtube.com/watch?v=dQw4w9WgXcQ';
$embedCode = convertYouTubeURLtoEmbed($userYouTubeURL);
echo $embedCode;
?>