如何在PHP中提取URL中的数据?附YouTube视频ID提取失败问题求助
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

