dongyuduan1890 2014-11-17 23:57
浏览 19
已采纳

PHP preg_match模式 - 小问题

I need a pattern which matches

youtube.com/watch?v=iNAMI8DQc8M

and

youtu.be/iNAMI8DQc8M

it should return the video id, in this case iNAMI8DQc8M

I tried this pattern:

youtu[.*][be|be\.com]\/+(.+)

but that does not work, I am not really good with regex.

  • 写回答

3条回答 默认 最新

  • dpnvrt3119 2014-11-17 23:59
    关注
    $str = 'youtube.com/watch?v=iNAMI8DQc8M';
    $id = get_id($str);
    
    function get_id($str) {
        $matches = array();
    
        if (preg_match('/youtu\.?be\/?(\.com\/watch\?v=)?([\w]+)/', $str, $matches)) {
            $id = $matches[2];
        }
        return $id;
    }
    

    It's extremely tolerant, but it works.

    We know youtu will be there no matter what, so there it is. youtu

    The first part checks for a . before be. It could be there, but doesn't need to be there. \.?be

    There is a check for the .com/watch?v= part, too, which is also unnecessary, but okay to have. (\.com\/watch\?v=)?

    After that, we match the video ID. ([\w]+)

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料