Home » Php » php – Parsing Youtube links automatically

php – Parsing Youtube links automatically

Posted by: admin July 12, 2020 Leave a comment

Questions:
$message = preg_replace("#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)&?.*?#i", "<iframe title=\"YouTube\" width=\"480\" height=\"390\" src=\"http://www.youtube.com/embed/$4\" frameborder=\"0\" allowfullscreen></iframe>", $message);

This works fine if youtube link looks like this:

http://www.youtube.com/watch?v=9DhSwsbKJQ4

but there is a problem if Youtube link looks like this:

http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music

The result is iframe and text feature=topvideos_music after iframe. Is there any way how to remove everything after & in Youtube link?

How to&Answers:

Why won’t you use parse_url() and parse_str() functions? It’s a much safer solution.

$url = 'http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music';
// $url = 'http://www.youtube.com/v/9DhSwsbKJQ4?feature=topvideos_music';

$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $parsedQueryString);

// URL in ?v=... form
if (isset($parsedQueryString['v'])) {
    $id = $parsedQueryString['v'];
}
// URL in /v/... form
else if (substr($parsedUrl['path'], 0, 3) == '/v/') {
    $id = substr($parsedUrl['path'], 3);
}
// invalid form
else {
    throw new ...;
}

Answer:

You’d be better off decomposing the URL with parse_url()/parse_str(), then rebuilding it from the ground up.

$url = 'http://www.youtube.com/....';

$url_parts = parse_url($url);

$query_parts = parse_str($parts['query']);

$v = $query_parts['v'];

$new_url = $url_parts['scheme']; // http
$new_url .= '://';
$new_url .= $url_parts['host']; // www.youtube.com
$new_url .= '/';
$new_url .= $url_parts['path']; // /
$new_url .= '?'
$new_url .= 'v' . $v; // v=....

While parseing with regex will work, at some point it’ll turn around and bite you. This is a bit more tedious, but safer in the long run.

Answer:

Regular Expressions

I am by no means a regex-pert, but the following removes the ampersand and everything following:

$vidpath = 'http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music';
echo preg_replace('/&.+/', '', $vidpath);

Produces http://www.youtube.com/watch?v=9DhSwsbKJQ4.

Blow it to Pieces!

The other option is to use explode() and split the string based on the occurences of &, resulting in an array where the 0 index contains your desired output.

echo array_shift( explode( '&', $vidpath ) );

In this case, array_shift() will return whatever item is at index 0, which will be your path.

Answer:

Short version.

$url = 'url_text';
$vidparser = parse_url($url);
parse_str($vidparser[query], $query);
$video_id = ($query['v']); 

Answer:

Yes. Try using this code before your one:

$message = 'http://www.youtube.com/watch?v=9DhSwsbKJQ4&feature=topvideos_music';
$message = explode( '&' , $message);
$message = $message[0];

Now, the $message variable is set to http://www.youtube.com/watch?v=9DhSwsbKJQ4.

Answer:

If all you want is the the videoID i suggest switchting to a regex like this:

/(http\:\/\/(www\.)?youtube\.com)\/watch\?v=([^&]+)/ism

Tested it on regextester.com

Answer:

You could, as mentioned previously, first get everything up to the &, or you could simply do the following (only typing the regex for convinence).

#(http://(www.)?youtube.com)?/(v/|watch\?v\=)([-|~_0-9A-Za-z]+)#i

in order to make it more generic, you could do the following:

#(:?(:?(:?www\.)?youtube\.(:?[^/]{2,5})/(:?v/|watch\?v\=))|(:?youtu.be/))([-|~_0-9A-Za-z]+)#

The regex doesn’t need to match everything. All the 😕 wich are to avoid the preg_replace to keep the reference, and by doing this it should match shortened URLs aswell. In this case, the reference would be stored in $1.

Answer:

Try pathinfo()

edit after comment: try executing this:

<?php
$url='http://www.site.com/foo/bar.php?dummy=param&dummy2=param2';
$array=pathinfo($url);
?><pre><?php print_r($array); ?></pre>
<?php
$params=strrchr($array['extension'],'?');
$params=str_replace('?','',$params);
$params_array=explode('&',$params);
foreach ($params_array as $each) {
$eacharray=explode('=',$each);
echo $eacharray[0]; //key
echo '<br />';
echo $eacharray[1]; //value
echo '<br />';
}
?>

the output will be:

Array
(
    [dirname] => http://www.site.com/foo
    [basename] => bar.php?dummy=param&dummy2=param2
    [extension] => php?dummy=param&dummy2=param2
)
dummy
param
dummy2
param2

Not a perfect example, but you can get all keys/values via this method.

edit2: sorry, I was in a hurry, re editing my postt for exactly what you need.

<?php
//code partially taken from php.net
$character='&';
$string='http://www.youtube.com/watch?v=asd123&feature=related&dummytext=true';
$whole_length = strlen($string); 
$right_length = (strlen(strstr($string, $character)) - 1); 
$left_length = ($whole_length - $right_length - 1); 

$piece = substr($string, 0, ($left_length));

echo $piece; //http://www.youtube.com/watch?v=asd123

?>