Grab the video ID only from youtube's URLs - php

How can I grab the video ID only from the youtube's URLs?
For instance,
http://www.youtube.com/watch?v=aPm3QVKlBJg
sometime the URLs contain other information after the 'v' like
http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index
but I don't want the other info, just video ID.
I only can think of using explode,
$url = "http://www.youtube.com/watch?v=aPm3QVKlBJg";
$pieces = explode("v=", $url);
but how to clean up the URLs like this?
http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index

You should never use regular expressions when the same thing can be accomplished through purpose-built functions.
You can use parse_url to break the URL up into its segments, and parse_str to break the query string portion into a key/value array:
$url = 'http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index'
// break the URL into its components
$parts = parse_url($url);
// $parts['query'] contains the query string: 'v=Z29MkJdMKqs&feature=grec_index'
// parse variables into key=>value array
$query = array();
parse_str($parts['query'], $query);
echo $query['v']; // Z29MkJdMKqs
echo $query['feature'] // grec_index
The alternate form of parse_str extracts variables into the current scope. You could build this into a function to find and return the v parameter:
// Returns null if video id doesn't exist in URL
function get_video_id($url) {
$parts = parse_url($url);
// Make sure $url had a query string
if (!array_key_exists('query', $parts))
return null;
parse_str($parts['query']);
// Return the 'v' parameter if it existed
return isset($v) ? $v : null;
}

Related

PHP parameters inside url cumulated parameter

lets say I have an url
http://www.somepage.com/clicker.php?id_campaign=8&id_email=9324&url=https://www.google.com/search?q=dog&sxsrf=ALeKk019eteEpAwVf2Fk4qYo7TiwhuMQ_Q:1596666153666&source=lnms&tbm=isch&sa=X&ved=2ahUKEwiqzqf3jIXrAhUisaQKHRayBWAQ_AUoAXoECBkQAw&biw=1920&bih=921#imgrc=M4wsJO0A7OQfTM
and im trying to get out the parameters id_campaign, id_email and url
however, using the code:
$url = htmlspecialchars_decode($url);
$parts = parse_url($url);
parse_str($parts['query'], $query);
when printing $parts['query'] it only gives me:
https://www.google.com/search?q=dog
because rest of the url it consider as another parameter...
so how do I get all the url parameter out of $url?
In an ideal scenario, the URLs passed within the query would be URL-encoded, as opposed to HTML-encoded.
What you could do in your case is manually replace all & by something temporary and then replace them all back after parsing the URL. This is not exactly pretty, but works:
$url = str_replace('&', '__TEMP__', $url);
$parts = parse_url($url);
parse_str($parts['query'], $query);
$urlParam = str_replace('__TEMP__', '&', $query['url']);
echo $urlParam;
Demo

if else on variable link input

I have a method of pulling Youtube video data from API links. I use Wordpress and ran into a snag.
In order to pull the thumbnail, views, uploader and video title I need the user to input the 11 character code at the end of watch?v=_______. This is documented with specific instructions for the user, but what if they ignore it and paste the whole url?
// the url 'code' the user should input.
_gXp4hdd2pk
// the wrong way, when the user pastes the whole url.
https://www.youtube.com/watch?v=_gXp4hdd2pk
If the user accidentally pastes the entire URL and not the 11 character code then is there a way I can use PHP to grab either the code or whats at the end of this url (11 characters after 'watch?v='?
Here is my PHP code to pull the data:
// $url is the code at the end of 'watch?v=' that the user inputs
$url = get_post_meta ($post->ID, 'youtube_url', $single = true);
// $code is a variable for placing the $url in a youtube link so I can output it to an API link
$code = 'http://www.youtube.com/watch?v=' . $url;
// $code is called at the end of this oembed code, allowing me to decode json data and pull elements from json to echo in my html
// echoed output returns json file. example: http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=_gXp4hdd2pk
$json = file_get_contents('http://www.youtube.com/oembed?url='.urlencode($code));
Im looking for something like...
"if user inputs code, use this block of code, else if user inputs whole url use a different block of code, else throw error."
Or... if they use the whole URL can PHP only use a specific section of that url...?
EDIT: Thank you for all the answers! I am new to PHP, so thank you all for your patience. It is difficult for graphic designers to learn PHP, even reading the PHP manual can give us headaches. All of your answers were great and the ones ive tested have worked. Thank you so much :)
Try this,
$code = 'https://www.youtube.com/watch?v=_gXp4hdd2pk';
if (filter_var($code, FILTER_VALIDATE_URL) == TRUE) {
// if `$code` is valid url
$code_arr = explode('?v=', $code);
$query_str = explode('&', $code_arr[1]);
$new_code = $query_str[0];
} else {
// if `$code` is not a valid url like '_gXp4hdd2pk'
$new_code = $code;
}
echo $new_code;
Here's a simple option for you to do, unless you want to use regex like Nisse Engström's Answer.
Using the function parse_url() you could do something like this:
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
now $video_id would return:
_gXp4hdd2pk
from the $url supplied in the above code.
I suggest you read the parse_url() documentation to ensure you understand and grasp it all :-)
Update
for your comment.
You'd use something like this to make sure the parsed value is a valid URL:
// this will check if valid url
if (filter_var($code, FILTER_VALIDATE_URL)) {
// its valid as it returned true
// so run the code
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
} else {
// they must have posted the video code as the if check returned false.
$video_id = $url;
}
Just try as follows ..
$url =" https://www.youtube.com/watch?v=_gXp4hdd2pk";
$url= explode('?v=', $url);
$endofurl = end($url);
echo $endofurl;
Replace $url variable with input .
I instruct my users to copy and paste the whole youtube url.
Then, I do this:
$video_url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk'; // this is from user input
$parsed_url = parse_url($video_url);
parse_str($parsed_url['query'], $query);
$vidID = isset($query['v']) ? $query['v'] : NULL;
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID; // this is used for the Api
$m = array();
if (preg_match ('#^(https?://www.youtube.com/watch\\?v=)?(.+)$#', $url, $m)) {
$code = $m[2];
} else {
/* No match */
}
The code uses a Regular Expression to match the user input (the subject) against a pattern. The pattern is enclosed in a pair of delimiters (#) of your choice. The rest of the pattern works like this:
^ matches the beginning of the string.
(...) creates a subpattern.
? matches 0 or 1 of the preceeding character or subpattern.
https? matches "http" or "https".
\? matches "?".
(.+) matches 1 or more arbitrary charactes. The . matches any character (except newline). + matches 1 or more of the preceeding character or subpattern.
$ matches the end of the string.
In other words, optionally match an http or https base URL, followed by the video code.
The matches are then written to $m. $m[0] contains the entire string, $m[1] contains the first subpattern (base URL) and $m[2] contains the second subpattern (code).

PHP: str_replace within a word/phrase

I am trying to set up a small script that can play youtube videos but thats kinda besides the point.
I have $ytlink which equals www.youtube.com/watch?v=3WAOxKOmR90
But I want to make it become www.youtube.com/embed/3WAOxKOmR90
Currently I have tried
$result = str_replace('https://youtube.com/watch?v=', "https://youtube.com/watch?v=", $ytlink);
But this returns it as standard
I have also tried
preg_replace('/https://youtube.com/watch?v=/, '/https://youtube.com/embed/', $ytlink);
but both of these dont work.
Instead of using ugly regexes, I recommend using parse_url() with parse_str(). This allows you to be flexible in the event that you want to change something or if Youtube decides to change their URL slightly.
$url = 'https://www.youtube.com/watch?v=3WAOxKOmR90';
// Parse the URL into parts
$parsed_url = parse_url($url);
// Get the whole query string
$query = $parsed_url['query'];
// Parse the query string into parts
parse_str($query, $params);
// Get the parameter you want
$v = $params['v'];
// Now re-build the URL how you want
echo $parsed_url['scheme'].'://'.$parsed_url['host'].'/embed/'.$v;
// Outputs: https://www.youtube.com/embed/3WAOxKOmR90
This works:
$ytlink = 'www.youtube.com/watch?v=3WAOxKOmR90';
$result = str_replace('watch?v=', 'embed/', $ytlink);
echo $result;
$url = 'www.youtube.com/watch?v=3WAOxKOmR90';
echo preg_replace('/.*?v=(\w+)/i', 'www.youtube.com/embed/$1', $url);

Extracting a string from a string where the string is variable

I want to get the individual ID from a youtube link so that I can use it later on, to pull other information such as its thumbnail image and insert it into the embedded iframe.
I notice there that all, I hope, of the urls on youtube start http://www.youtube.com/watch?v= Unique video ID and then depending on a few things can end something like &list=RD02M5u5zXVmoHM. But the unique id always has a & after it and the watch?v= before. Is this the best way to do it? Have a written this correctly?
$link=$_POST['link'];
$link_id=str_replace('http://www.youtube.com/watch?v=', '', $link);
$link_id=strstr($link_id, '&', true);
This comes from form data. Is there anything other variables from youtube URLs I may encounter?
What you want to do is use: http://php.net/pase_url and http://php.net/parse_str like this:
<?php
$info = parse_url("https://www.youtube.com/watch?v=DA57FOJSdM8");
parse_str($info["query"], $query);
print_r($query);
// Outputs: Array ( [v] => DA57FOJSdM8 )
A combination of parse_url() and parse_str() would be a simpler way where PHP handles the dirty work for you. Example:
$video_id = false;
$url_parts = parse_url($link);
$query_params = array();
if (isset($url_parts['query']))
{
parse_str($url_parts['query'], $query_params);
}
if (isset($query_params['v']))
{
$video_id = $query_params['v'];
}
And now $video_id contains the ID you need.

Remove specific parameter from URL while preserving other parameters

I want remove a parameter from a URL:
$linkExample1='https://stackoverflow.com/?name=alaa&counter=1';
$linkExample2='https://stackoverflow.com/?counter=4&star=5';
I am trying to get this result:
https://stackoverflow.com/?name=alaa&
https://stackoverflow.com/?&star=5
I am trying to do it using preg_replace, but I've no idea how it can be done.
$link = preg_replace('~(\?|&)counter=[^&]*~','$1',$link);
Relying on regular expressions can screw things up sometimes..
You should use, the parse_url() function which breaks up the entire URL and presents it to you as an associative array.
Once you have that array, you can edit it as you wish and remove parameters.
Once, completed, use the http_build_url() function to rebuild the URL with the changes made.
Check the docs here..
Parse_Url Http_build_query()
EDIT
Whoops, forgot to mention. After you get the parameter string, youll obviously need to separate the parameters as individual ones. For this you can supply the string as input to the parse_str() function.
You can even use explode() with & as the delimeter to get this done.
I would recommend using a combination of parse_url() and http_build_query().
Handle it correctly! !
remove_query('http://example.com/?a=valueWith**&**inside&b=value');
Code:
function remove_query($url, $which_argument=false){
return preg_replace( '/'. ($which_argument ? '(\&|)'.$which_argument.'(\=(.*?)((?=&(?!amp\;))|$)|(.*?)\b)' : '(\?.*)').'/i' , '', $url);
}
A code example how I would grab a requested URL and remove a parameter called "name", then reload the page:
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //complete url
$parts = parse_url($url);
parse_str($parts['query'], $query); //grab the query part
unset($query['name']); //remove a parameter from query
$dest_query = http_build_query($query); //rebuild new query
$dest_url=(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http").'://'.$parts['path'].'?'.$dest_query; //add query to host
header("Location: ".$dest_url); //reload page
parse_url() and parse_str() are buggy. Regular expressions can work but have the tendency to break. If you want to correctly deconstruct, make changes, and then reconstruct a URL, you should look at:
http://barebonescms.com/documentation/ultimate_web_scraper_toolkit/
ExtractURL() generates parse_url()-like output but does much more (and does it right). CondenseURL() takes an array from ExtractURL() and constructs a new URL from the information. Both functions are in the 'support/http.php' file.
Years later...
$_GET can be manipulated like any other array in PHP. Simply unset the key and create the http query using the http_build_query function.
// Populate _GET with sample data...
$_GET = array(
'value_a' => "A",
'key_to_remove' => "Don't delete me bro!",
'value_b' => "B"
);
// Should output everything...
// "value_a=A&key_to_remove=Don%27t+delete+me+bro%21&value_b=B"
echo "\n".http_build_query( $_GET );
// Remove the key from _GET...
unset( $_GET[ 'key_to_remove' ] );
// Should output everything else...
// "value_a=A&value_b=B"
echo "\n".http_build_query( $_GET );
This is working for me:
function removeParameterFromUrl($url, $key)
{
$parsed = parse_url($url);
$path = $parsed['path'];
unset($_GET[$key]);
if(!empty(http_build_query($_GET))){
return $path .'?'. http_build_query($_GET);
} else return $path;
}

Categories