0

i saw some things look a like but not the same, i hope you can assist:

i am trying to execute the first result from youtube search results by

parse youtube search result page and find this: (belong to the first video)

<img alt="Thumbnail" src="http://i4.ytimg.com/vi/kUJLn7645Zs/default.jpg">

then i want to get the video code which is this: (kUJLn7645Zs)

this is my code and something doesn't work, please assist

$res = file_get_contents("http://www.youtube.com/results?search_query=take+me");
preg_match_all('/<img\s[a-zA-Z0-9=\'\":\/.()_@&\s]*>/',$res,$matches);

$str = $matches[0][0];
$tempArray = array();
$tempArray = explode('/',$str);
echo $tempArray[count($tempArray) - 2];
3
  • Why are you using preg_match_all() if you only want the first result? Commented Jul 27, 2011 at 5:11
  • actually i want the first 5, that was jsut an example Commented Jul 27, 2011 at 5:16
  • if you can use zend, using youtube api would be much lighter than loading a page Commented Jul 27, 2011 at 5:51

4 Answers 4

1

Why not :

if(preg_match_all('/\<img [^\>]* src\="(https?:)?\/\/i[0-9]\.ytimg\.com\/vi\/([_a-zA-Z0-9-]+)\/default\.jpg" ?[^\>]*\>/',$res,$matches))
{
  $firstVid= $matches[2][0];
}
else
{
  $firstVid= "";
}

print_r($matches);

?

Sign up to request clarification or add additional context in comments.

5 Comments

hey, that doesnt return a thing. did you check it?
so the regex doesnt fit. can you check again, because it doesnt help me :)
it was fitting with the <img /> you gave in the example, I've changed my answer so it fit also with what I get from youtube
i try this: if(preg_match_all('/\<img [^\>]* src\="(https?:)?\/\/i[0-9]+\.ytimg\.com\/vi\/([_a-zA-Z0-9-]+)\/default\.jpg" ?\>/',$res,$matches)) { $firstVid= $matches[2][0]; echo $firstVid; } else { $firstVid= ""; } still doesnt return
I tried from somewhere else and the code of image was <img src="http://i4.ytimg.com/vi/Cvdk7vB3jM4/default.jpg" alt="Thumbnail" > I've changed my post to match it too.
0

it's hard to use regex to parse html.

Try using a pre-made framework like SimpleHtmlDom

Comments

0

I would rather us

explode("/", "myvar");

And just take the part that interests me

Comments

0

this is the complete answer.

thank you all and a big thank you to Enki :)

$res = file_get_contents("http://www.youtube.com/results?search_query=take+me");
if(preg_match_all('/\<img [^\>]* src\="(https?:)?\/\/i[0-9]\.ytimg\.com\/vi\/([_a-zA-Z0-9-]+)\/default\.jpg" ?[^\>]*\>/',$res,$matches))
{
  $firstVid= $matches[0][0];
}
else
{
  $firstVid= "";
}

$tempArray = array();
$tempArray = explode('/',$firstVid);
echo $tempArray[count($tempArray) - 2];

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.