Pick specific snippet from a string

Asked

Viewed 98 times

3

I have a youtube url and would like to take only the snippet of the variable "v".

used this: $video = mb_substr('https://www.youtube.com/watch?v=k4qVkWh1EAo', 32), returns the value I need, but I wonder if there is another way.

You can directly access the variable "v" and take its value, it is possible in a string?

  • He even researched whether they had already answered this question?

1 answer

4


You can use the parse_str and parse_url:

<?php
$url = "https://www.youtube.com/watch?v=k4qVkWh1EAo";
parse_str( parse_url( $url, PHP_URL_QUERY ), $vars);
echo $vars['v'];    
// Saída: k4qVkWh1EAo
?>

parse_str

Converts the string into variables


parse_url

Interprets a URL and returns its components

Observing: It won’t work if the link is in the following format https://www.youtube.com/v/k4qVkWh1EAo/

Soen reference: PHP Regex to get youtube video ID?

  • 1

    Nice to put the reference when copying a reply... http://stackoverflow.com/a/3393008/2072674

  • 1

    @Added Kennyrafael

  • 1

    But the answer does not deserve -2 because of this I believe only one sign in comment ....

  • 2

    I also added the links for the documentation of the two methods and the brief explanation found in the manual

  • 1

    Good, it worked! .

  • @Juniorcastro only see that I put an observation at the end, I do not know if it is your case. Don’t forget to mark it so it can be used if someone has a similar question!

  • Indeed, no one else agrees that this question is duplicated?

  • 2

    In fact @Sorack this field will be filled through a text field coming from wordpress, so the user copies the link url and pastes it in admin, I format the output. So don’t need the guy to go on youtube, embed etc...

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.