Home > Backend Development > PHP Tutorial > How Can I Extract YouTube Video IDs from URLs Using PHP?

How Can I Extract YouTube Video IDs from URLs Using PHP?

Susan Sarandon
Release: 2024-12-01 16:38:15
Original
171 people have browsed it

How Can I Extract YouTube Video IDs from URLs Using PHP?

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&amp;feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v']; // Output: C4kxS1ksqtw
?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template