Convert BBCode YouTube tags to HTML with embedded video ID

Hey folks, I’m working on a blog that needs to change BBCode YouTube tags into HTML. I’m trying to turn this:

[youtube=http://www.youtube.com/watch?v=VIDEO_ID&feature=channel]

Into something like this:

<iframe width="400" height="245" src="https://www.youtube.com/embed/VIDEO_ID" frameborder="0" allowfullscreen></iframe>

I’ve got a main function that calls different process functions, including one for YouTube videos. It looks like this:

$text = preg_replace('/\[youtube=([^\]]*)\]/', 'handleYouTubeLinks("$1")', $text);

The handleYouTubeLinks() function gets the URL fine, but I’m having trouble splitting it to get the video ID. Even simple stuff like splitting on ‘u’ or ‘tube’ isn’t working. Any ideas what I’m doing wrong? Thanks!

I’ve tackled this issue before in a content management system I built. Here’s a robust solution that’s worked well for me:

function handleYouTubeLinks($url) {
$pattern = ‘#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#’;
preg_match($pattern, $url, $matches);
if (!empty($matches[0])) {
$videoId = $matches[0];
return “”;
}
return $url;
}

This regex covers various YouTube URL formats, including mobile and shortened links. It’s been reliable across different projects.

One tip: consider adding a fallback for when the regex fails to match. You could display a link to the original URL instead of an empty iframe. This improves user experience if the URL format changes unexpectedly.

I’ve dealt with this exact issue in a project where we needed to convert various video embed formats. While the regex approach works, I found it more maintainable to use PHP’s parse_url() function combined with parse_str(). Here’s a solution that’s served me well:

function handleYouTubeLinks($url) {
    $parsedUrl = parse_url($url);
    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $params);
        if (isset($params['v'])) {
            $videoId = $params['v'];
            return '<iframe width=\"400\" height=\"245\" src=\"https://www.youtube.com/embed/' . $videoId . '\" frameborder=\"0\" allowfullscreen></iframe>';
        }
    }
    return $url; // Return original if we couldn't parse
}

This approach is more readable and easier to modify if YouTube changes their URL structure in the future. It’s also less prone to regex-related errors.

hey lucask, try using preg_match() to extract the video ID. something like this might work:

function handleYouTubeLinks($url) {
preg_match(‘/[?&]v=([^&]+)/’, $url, $match);
$videoId = $match[1];
return ‘<iframe width="400" height="245" src="YouTube’ + $videoId + ‘" frameborder="0" allowfullscreen>’;
}

this should grab the ID and build the iframe for ya. lmk if u need more help!

hey lucask, have u tried using str_replace() instead? might be easier. like this:

function handleYouTubeLinks($url) {
$id = str_replace(‘YouTube’, ‘’, $url);
$id = explode(‘&’, $id)[0];
return “”;
}

works for me. give it a shot!

yo lucask, i had a similar problem. try this:

function handleYouTubeLinks($url) {
$parts = explode(‘v=’, $url);
$videoId = explode(‘&’, $parts[1])[0];
return “”;
}

it splits the url and grabs the ID. works for me, hope it helps u too!

I’ve encountered a similar issue before when working on a forum migration project. The key is to use a more robust regex pattern that can handle different YouTube URL formats. Here’s a function that worked well for me:

function handleYouTubeLinks($url) {
    $pattern = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i';
    if (preg_match($pattern, $url, $match)) {
        $videoId = $match[1];
        return '<iframe width="400" height="245" src="https://www.youtube.com/embed/' . $videoId . '" frameborder="0" allowfullscreen></iframe>';
    }
    return $url; // Return original URL if no match found
}

This regex handles various YouTube URL formats, including shortened youtu.be links. It’s been reliable in my experience, even with edge cases. Hope this helps solve your problem!

hey lucask, i had a similar problem. heres wat worked for me:

function handleYouTubeLinks($url) {
$id = explode(‘v=’, $url)[1];
$id = explode(‘&’, $id)[0];
return “”;
}

its simple but gets the job done. lmk if u need more help!

As someone who’s been developing forum software for years, I’ve dealt with this YouTube embed issue many times. Here’s a trick I’ve found that works reliably:

function handleYouTubeLinks($url) {
$videoId = ‘’;
if (strpos($url, ‘youtu.be/’) !== false) {
$videoId = substr($url, strrpos($url, ‘/’) + 1);
} elseif (strpos($url, ‘youtube.com’) !== false) {
parse_str(parse_url($url, PHP_URL_QUERY), $params);
$videoId = isset($params[‘v’]) ? $params[‘v’] : ‘’;
}

return $videoId ? sprintf('<iframe width="400" height="245" src="https://www.youtube.com/embed/%s" frameborder="0" allowfullscreen></iframe>', $videoId) : $url;

}

This handles both youtu.be and youtube.com links, and it’s fast because it avoids regex when possible. It’s served me well across multiple projects and forum migrations. Just remember to sanitize your inputs to prevent XSS attacks.

Having worked on several content management systems, I’ve found that a combination of regular expressions and URL parsing tends to be the most robust solution for handling YouTube links. Here’s an approach I’ve used successfully:

function handleYouTubeLinks($url) {
$parsed = parse_url($url);
$query = isset($parsed[‘query’]) ? $parsed[‘query’] : ‘’;
parse_str($query, $params);

$videoId = '';
if (isset($params['v'])) {
    $videoId = $params['v'];
} elseif (preg_match('/^https?:\/\/youtu\.be\/([\w-]+)/', $url, $matches)) {
    $videoId = $matches[1];
}

if ($videoId) {
    return sprintf('<iframe width="400" height="245" src="https://www.youtube.com/embed/%s" frameborder="0" allowfullscreen></iframe>', $videoId);
}

return $url;

}

This method handles both standard YouTube URLs and shortened youtu.be links. It’s also more flexible if YouTube changes their URL structure in the future.