自动解析Youtube链接

tfe*_*tfe 8 php youtube

$message = preg_replace("#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i", "<iframe title=\"YouTube\" width=\"480\" height=\"390\" src=\"http://www.youtube.com/embed/$4\" frameborder=\"0\" allowfullscreen></iframe>", $message);
Run Code Online (Sandbox Code Playgroud)

如果youtube链接如下所示,这可以正常工作:

http://www.youtube.com/watch?v=9DhSwsbKJQ4

但如果Youtube链接看起来像这样,则会出现问题:

http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music

结果是iframe feature=topvideos_music之后的iframe 和文本.&在Youtube链接后有什么方法可以删除所有内容吗?

Sam*_*son 1

常用表达

我绝不是正则表达式专家,但以下内容删除了&符号和以下所有内容:

$vidpath = 'http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music';
echo preg_replace('/&.+/', '', $vidpath);
Run Code Online (Sandbox Code Playgroud)

产生http://www.youtube.com/watch?v=9DhSwsbKJQ4.

把它炸成碎片!

另一个选项是explode()根据 的出现情况使用并拆分字符串&,从而生成一个数组,其中0索引包含所需的输出。

echo array_shift( explode( '&', $vidpath ) );
Run Code Online (Sandbox Code Playgroud)

在这种情况下,array_shift()将返回 index 处的任何项目0,这将是您的路径。