I’m working on a WordPress plugin and need help with a PHP regex. My goal is to find YouTube BBCode tags and turn them into embed codes.
Here’s what I want to do:
- Find this pattern:
[youtube=http://www.youtube.com/watch?v=ABCDEFGH&hl=en&fs=1]
- Change it to:
param name="movie" value="http://www.youtube.com/v/ABCDEFGH&hl=en&fs=1&rel=0
The tricky part is keeping the video ID (ABCDEFGH in this example) the same.
Can someone show me how to do this with preg_replace()
? It would be great if you could explain the regex parts too. I’m new to this and want to learn how it works.
Thanks for any help!
I’ve tackled a similar issue in one of my projects. Here’s a PHP solution using preg_replace() that should work for you:
$pattern = ‘/[youtube=http://www.youtube.com/watch?v=([A-Za-z0-9_-]+)&hl=en&fs=1]/’;
$replacement = ‘param name=“movie” value=“http://www.youtube.com/v/$1&hl=en&fs=1&rel=0”’;
$result = preg_replace($pattern, $replacement, $input_string);
The pattern matches the BBCode format you described. The key is the ([A-Za-z0-9_-]+) part, which captures the video ID. In the replacement, $1 refers to this captured ID.
This regex assumes the BBCode is exactly as you’ve shown. You might need to adjust it if there are variations in the format. Hope this helps with your WordPress plugin!
As someone who’s worked extensively with WordPress and BBCode parsing, I can offer a slightly different approach that might be more flexible for your needs:
function convert_youtube_bbcode($content) {
$pattern = '/\[youtube=(https?:\/\/(?:www\.)?youtube\.com\/watch\?v=([\w-]+)(?:&\S*)?)]\s*/i';
$replacement = '<iframe width="560" height="315" src="https://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe>';
return preg_replace($pattern, $replacement, $content);
}
This function not only handles the conversion but also creates a proper iframe embed, which is more modern and flexible than the old param approach. It also accounts for potential variations in the YouTube URL format. You can easily adjust the iframe dimensions or add more parameters as needed.
To use it, just apply this function to your post content before displaying it. It’s a more robust solution that should work well within a WordPress plugin context.