How to Use Regex to Extract YouTube Video IDs
To obtain YouTube video IDs, even with additional GET variables present in the URL, a combination of parse_url() and parse_str() can be employed.
Using parse_url(), the URL is divided into an array containing various information. Specify PHP_URL_QUERY as the second argument to isolate the relevant query string in this case.
Now that you have the query string, you can use parse_str() to extract variables from it, just like GET would with a normal query string. In this case, it will create $v and $feature variables, but only $v is needed.
For safety measures, it's recommended to store the variables in an array rather than directly in the namespace, to prevent accidental overwriting of existing variables.
Here's a complete example:
<?php $url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate"; parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars ); echo $my_array_of_vars['v']; // Output: C4kxS1ksqtw ?>
By following these steps, you can easily retrieve YouTube video IDs using PHP, regardless of any additional GET variables present in the URL.
The above is the detailed content of How Can I Extract YouTube Video IDs from URLs Using PHP?. For more information, please follow other related articles on the PHP Chinese website!