3

I want to get the id of the youtube video i used this code :

$url = $video->link;
  if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $videoId)) {
    $values = $videoId[1];
  } else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $videoId)) {
    $values = $videoId[1];
  } else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $videoId)) {
    $values = $videoId[1];
  } else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $videoId)) {
    $values = $videoId[1];
  }
  else if (preg_match('/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/', $url, $id)) {
      $values = $videoId[1];
  } else {   
  // not an youtube video
  }

I get this error "htmlspecialchars() expects parameter 1 to be string, array given" . the error is that this code give me an array when i want a string is there a solution to get the id of the youtube video in a string format ?

Youssef Boudaya
  • 887
  • 2
  • 17
  • 29

1 Answers1

3

Use parse_url() and parse_str()

$url="http://www.youtube.com/watch?v=C4kxS1ksqtw"

parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );

echo $my_array_of_vars['v'];    

 // Output: C4kxS1ksqtw

Source: https://stackoverflow.com/a/3393008/320487

References:

http://php.net/manual/en/function.parse-url.php

http://php.net/manual/en/function.parse-str.php

  • using your code i did this: parse_str( parse_url( $url, PHP_URL_QUERY ), $youtube ); $id = $youtube['v']; it worked fine or i just added this line to my initial code: $id = $videoId[1]; – Youssef Boudaya Feb 01 '18 at 09:30