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 ?

4
  • plz dd($videoId[1]) Commented Feb 1, 2018 at 9:21
  • array:2 [▼ 0 => "youtube.com/watch?v=Y9oLMvwe4Eg" 1 => "Y9oLMvwe4Eg" ] Commented Feb 1, 2018 at 9:22
  • is this $videoId or videoId[1] Commented Feb 1, 2018 at 9:24
  • dump in the question not here Commented Feb 1, 2018 at 9:24

1 Answer 1

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

1
  • 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]; Commented Feb 1, 2018 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.