【问题标题】:Function preg_match() is not returning any value函数 preg_match() 没有返回任何值
【发布时间】:2010-12-16 06:31:55
【问题描述】:

我正在使用preg_match() 来匹配字符串中的模式并进一步解析它们...但它没有返回任何值...

实际上,我是用它来通过查看标题信息来获取视频的。

$url = "http://www.youtube.com/watch?v=" . $video_id;
$this->req =& new HTTP_Request($url);
$response = $this->req->sendRequest();
$rescode  = $this->req->getResponseCode();

echo "++response code++$rescode";
echo "***$response***";

if (PEAR::isError($response)) {
    echo "<b>Please check whether the video added or not </b>";
} 
else {
    $page = $this->req->getResponseBody();
    //echo "=====$page====";

    preg_match('/"videoplayback": "(.*?)"/', $page, $match);

    $var_id = $match[1];
    echo "+++$var_id+++;
}

如果我用下面的代码替换 preg_match 调用,一切都可以正常工作,但这不是我需要的......

preg_match('/"video_id": "(.*?)"/', $page, $match);

我要匹配的字符串是:

http://v17.lscache6.c.youtube.com/videoplayback?ip=0.0.0.0&sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Calgorithm%2Cburst%2Cfactor%2Coc%3AU0dYR1RMVl9FSkNNOF9MRlpB&fexp=906320&algorithm=throttle-factor&itag=34&ipbits=0&burst=40&sver=3&expire=1292418000&key=yt1&signature=32DD3C5BF016489B43D15493F68ACCDE2AA720B5.95F66ACBE6FDFBC60978A14075A28020E083E8A8&factor=1.25&id=39743a9fde40b0dd&

我该如何解决这个问题?

【问题讨论】:

  • @kvihayhari:你有没有尝试转储页面的内容,就像你没有点击 404 或其他页面一样......
  • 您是否要从"videoplayback": "some_string" 中提取some_string?如果是这样,您提供的字符串与您的模式不匹配。
  • 行回显"=====$page====";做得很好并打印所有内容。我只需要获取其中包含字符串'videoplayback'的整个url。一旦我得到完整的 url,我就会使用该 url 的 file_get_contents
  • 有一点需要注意,尽管根据您的陈述,这听起来不像您的问题,是 .* 吗?是懒惰的,匹配空字符串没有问题。检验这一理论的一种方法是尝试改变 .*?到 .+?,看看你是否得到一个字符匹配。
  • videoplayback 未在示例中引用。输入中实际上应该有一个文字 "videoplayback" 吗?该代码看起来更像是试图匹配HTML 页面的内容,而不是URL。语句 "The string that I'm trying to match is..." 似乎不正确。不是URL指向的页面的content吗?

标签: php regex preg-match


【解决方案1】:

如果您只需要检查 $page 中是否存在“videoplayback”,那么您可以使用:

if (preg_match("/.*videoplayback.*/", $page){
    // Use the whole $page URL
}

无需捕获任何内部匹配组件。

不过,您可能希望使用更紧凑的模式:

$pattern = "/.*youtube\.com\/videoplayback\?.*/";

【讨论】:

    【解决方案2】:

    试试:

    preg_match('/\"videoplayback\"\:\s\"(.*)\"/iU', $page, $match);
    

    如果它不起作用,也试试这个:

    preg_match('/\"videoplayback\"\:\s\"([^\"]*)\"/iU', $page, $match);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多