【问题标题】:preg_match returns null when the haystack is an exec() output当 haystack 是 exec() 输出时,preg_match 返回 null
【发布时间】:2013-04-13 19:36:07
【问题描述】:

我正在尝试在我使用exec() 运行的 Linux 命令的输出上运行一些正则表达式。 preg_match 在将exec() 输出作为干草堆插入时返回NULL,但是当我将此输出的相同副本放入字符串中并将其用作干草堆时,preg_match 工作正常并输出预期的数组。

代码:

exec("/usr/local/bin/ffmpeg -i video.flv 2>&1 | grep Duration", $output);
//$output[0] will be: "Duration: 00:01:00.08, start: 0.042000, bitrate: 164 kb/s"    
$string = $output[0];    
//This regex is to extract the duration, "00:01:00", from the output.
$pattern = "/(^Duration:) ([^&]+)(.[0-9][0-9])(, start)/";    
preg_match($pattern, $string, $matches);
print_r($matches[2]);
//The result should be "00:01:00" but the whole $matches array is empty instead.

//If I added the result of output[0] manually into a string it works fine.
$str = "Duration: 00:01:00.08, start: 0.042000, bitrate: 164 kb/s";
preg_match($pattern, $str, $matches_);
print_r($matches_[2]);
//Outputs "00:01:00" and everything is working fine.

//Just to make sure, I printed $str and $string to see if there is any difference
echo $str."\n".$string;
//The output is:
//Duration: 00:01:00.08, start: 0.042000, bitrate: 164 kb/s
//Duration: 00:01:00.08, start: 0.042000, bitrate: 164 kb/s    

【问题讨论】:

  • 尝试trim字符串。您可能在开头或结尾有一些不可见的字符。
  • 你检查过准确的$output吗?另外,看看FFprobe,它可以提供格式更好的输出。
  • 谢谢戴夫。那行得通。 +1 的答案。我会试试 FFprobe。

标签: php regex arrays preg-match


【解决方案1】:

使用以下 echo 命令,使用单引号分隔字符串:

echo "'$str'\n'$string'";

输出:

'Duration: 00:01:00.08, start: 0.042000, bitrate: 164 kb/s'
'  Duration: 00:01:12.66, start: 0.000000, bitrate: 127 kb/s'

你看,它们不一样。 ffmpeg 在字符串前面添加空格。

但是,如果您将模式更改为:

$pattern = "/(Duration:) ([^&]+)(.[0-9][0-9])(, start)/";

请注意,我已将^ 放在Duration 前面。现在模式匹配了,尽管字符串前面有一些空格。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2014-07-08
    • 2011-08-01
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多