You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中提取URL中的数据?附YouTube视频ID提取失败问题求助

How to Extract YouTube Video ID from Your URL String

Hey there! Let's fix this issue together. The problem with your current code is that the regular expression you used (#/mk_([^/]*)#) doesn't match anything in your input URL—there's no /mk_ segment in that YouTube link at all, which is why you're getting no results.

Here are two reliable ways to extract the video ID JCA2PjAHmNw from your string:

Method 1: Targeted Regular Expression

Since the video ID comes right after v= and ends at the first & (your URL uses &, which is the HTML-encoded version of &), we can use a regex that captures everything between v= and the next &:

$input = 'https://www.youtube.com/watch?v=JCA2PjAHmNw&list=RDGMEM_v2KDBP3d4f8uT-ilrs8fQVMXJu6RlDf2O4&index=7';

if (preg_match('#v=([^&]*)#', $input, $matches)) {
    echo $matches[1]; // Outputs: JCA2PjAHmNw
}
  • v= matches the start of the video ID parameter
  • ([^&]*) captures all characters until the first & (this works even with & because the & is still the delimiter)

Method 2: Use URL Parsing Functions (More Robust)

For a more reliable approach that handles any order of URL parameters or encoding quirks, use PHP's built-in URL parsing tools:

$input = 'https://www.youtube.com/watch?v=JCA2PjAHmNw&list=RDGMEM_v2KDBP3d4f8uT-ilrs8fQVMXJu6RlDf2O4&index=7';

// First, replace HTML-encoded & with regular &
$cleanQueryString = str_replace('&', '&', parse_url($input, PHP_URL_QUERY));

// Parse the query string into an array of parameters
parse_str($cleanQueryString, $urlParams);

echo $urlParams['v']; // Outputs: JCA2PjAHmNw

This method is better because it doesn't rely on the position of the v parameter—even if the URL had other parameters before v, it would still grab the correct value.

内容的提问来源于stack exchange,提问作者Valerius Romulus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 11:23:26