2011-07-27 85 views
0

我看到有些東西看起來像,但不一樣的,我希望你能幫助:問題,PHP和正則表達式

我試圖通過

解析YouTube搜索執行從YouTube搜索結果的第一個結果結果頁面,找到這個:(屬於第一視頻)

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

的話,我想要得到的視頻代碼是這樣的:(kUJLn7645Zs)

這是我的代碼和一些事情不工作,請協助

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

$str = $matches[0][0]; 
$tempArray = array(); 
$tempArray = explode('/',$str); 
echo $tempArray[count($tempArray) - 2]; 
+0

爲什麼你使用'preg_match_all()'如果你只想在第一個結果? – Phil

+0

實際上我想要第一個5,這是一個例子 –

+0

,如果你可以使用zend,使用[youtube api](http://code.google.com/intl/fr-FR/apis/youtube/2.0/developers_guide_php。 HTML#Searching_for_Videos)會比加載一個頁面 – Enki

回答

1

爲什麼不:

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); 

+0

輕很多,這不會返回一個東西。你檢查了嗎? –

+0

所以正則表達式不適合。你能再次檢查,因爲它不幫我:) –

+0

它適合於你在示例中給出的,我改變了我的答案,所以它也適合我從YouTube獲得的內容 – Enki

0

很難用正則表達式來解析html。

使用預製的框架狀SimpleHtmlDom

0

試試我寧願我們

explode("/", "myvar"); 

而只是把我感興趣

0

這是一個完整的答案的一部分。

謝謝大家和非常感謝恩基:)

$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]; 
+0

如果恩基的答案幫助你,你應該接受它 - http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Phil