php和regex的问题

时间:2011-07-27 05:00:48

标签: php regex

我看到有些东西看起来像但不一样,我希望你可以提供帮助:

我正在尝试通过

执行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=\'\":\/.()_@&\s]*>/',$res,$matches);

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

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

很难用正则表达式解析html。

尝试使用预制框架,例如SimpleHtmlDom

答案 2 :(得分:0)

我宁愿我们

explode("/", "myvar");

然后选择我感兴趣的部分

答案 3 :(得分:0)

这是完整的答案。

谢谢大家,非常感谢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];