dounan4479 2014-11-29 23:58
浏览 58
已采纳

从URL获取最后11个字符

I got this code:

if(preg_match("/^(?:https?:\/\/)?(?:www\.)?youtu(.be\/|be\.com\/watch\?v=)(\w{11})$/", $url)){
        preg_match("/^(?:https?:\/\/)?(?:www\.)?youtu(.be\/|be\.com\/watch\?v=)(\w{11})$/", $url, $matches);
        $vid = str_replace(' ', '', $matches[0]);
}

That pretty much checks if the URL is a Youtube video. How do I assign the last 11 characters from the URL to the $vid variable?

Example:

URL: https://www.youtube.com/watch?v=ASDASDASDAS

$vid = ASDASDASDAS
  • 写回答

4条回答 默认 最新

  • donglu9978 2014-11-30 00:06
    关注

    First, you don't want to check for the last 11 characters, because the video ID might be changed any time to a different length. What you should always do is make something flexible enough. So in this case, you should check for ?.*v=([^&]+), since that will get the match until the next &. So your code would look like this:

    //make this a variable, since you're using it multiple times.
    $re = "/^(?:https?:\/\/)?(?:www\.)?youtu(.be|be\.com)\/watch\?.*?v=([^&#]+).*$/";
    if (preg_match($re, $url)){
            preg_match($re, $url, $matches);
            $vid = $matches[2]; //the 2nd group in the match, so the 2nd set of ()s
    }
    

    In that code, video urls that contain other URL parameters will also still work, and it's much more flexible with the length of the video ID.

    Demo - look to the right where it says 2., it will mention the video ID there (which is what's put inside $vid).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器