Im building my own forum where you can use diffrent types of BBcode and one of them is [youtube][/youtube] to embed youtube videos,
The idea is to make it idiot-proof, the user can enter the full lenght url or just the code to the video like this
[youtube]http://www.youtube.com/watch?v=AJ3_kndmeCg[/youtube]
[youtube]http://www.youtube.com/watch?v=AJ3_kndmeCg&feature=related[/youtube] [youtube]AJ3_kndmeCg[/youtube]
Here is my code that get the code out of a full lenght url,
<?php
$getpost=$_POST['post'];
$getpost=preg_replace("'\[youtube\].*?=(.*?)&.*?\[/youtube\]'is",'yt link is \\1',$getpost); 开发者_运维知识库
$getpost=preg_replace("'\[youtube\].*?=(.*?)\[/youtube\]'is",'yt link is \\1',$getpost);
$getpost=preg_replace("'\[youtube\](.*?)\[/youtube\]'is",'yt link is \\1',$getpost);
?>
The results are:
yt link is AJ3_kndmeCg
yt link is AJ3_kndmeCg yt link is AJ3_kndmeCg
It works perfectly if I only want to embed 3 youtube videos,
But if i wanted to embed 6 youtube videos like this:
[youtube]http://www.youtube.com/watch?v=AJ3_kndmeCg[/youtube] [youtube]http://www.youtube.com/watch?v=AJ3_kndmeCg&feature=related[/youtube] [youtube]AJ3_kndmeCg[/youtube]
[youtube]http://www.youtube.com/watch?v=AJ3_kndmeCg[/youtube] [youtube]http://www.youtube.com/watch?v=AJ3_kndmeCg&feature=related[/youtube] [youtube]AJ3_kndmeCg[/youtube]
The results are:
yt link is AJ3_kndmeCg
yt link is AJ3_kndmeCg[/youtube] yt link is AJ3_kndmeCg yt link is http://www.youtube.com/watch?v=AJ3_kndmeCg [youtube]AJ3_kndmeCg
Do you see that^^ the tags still remain on two lines and one of the lines show a full lenght URL,
I'd rather use an existing BBCode parsing library like http://www.christian-seiler.de/projekte/php/bbcode/index_en.html which also allows you to define your own bb tags, and turn them into the HTML you want.
;)
Wow, this was a real toughie of a regex to write.
Got it for you in one:
$getpost=preg_replace('@\[youtube\].*?(?:v=)?([^?&[]+)(&[^[]*)?\[/youtube\]@is',
'yt link is \\1', $getpost);
This will work for all the cases you supplied. It will not work if the link begins with a part other than 'v=' (for example, 'http://www.youtube.com/watch?foo=bar&v=AJ3_kndmeCg').
Enjoy!
精彩评论