php - 当 haystack 是 exec() 输出时,preg_match 返回 null

标签 php regex arrays preg-match

我正在尝试对使用 exec() 运行的 Linux 命令的输出运行一些正则表达式。当将 exec() 输出作为干草堆插入时,preg_match 返回 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    

最佳答案

使用以下 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 前面。现在,尽管字符串前面有一些空格,但模式仍然匹配。

关于php - 当 haystack 是 exec() 输出时,preg_match 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15992044/

相关文章:

java - 使用 RowFilter (regexFilter) 匹配括号

python - 保留满足两个或多个条件的 numpy 数组的值

php - 在 laravel 5.4 中上传图片时移动 'tmp' 目录不起作用

php - 是否存在未调用 PHP 中的析构函数的情况?

python - 无法读取基于正则表达式的文件

c - C中函数指针数组的数组

javascript - 如何从 JSON 生成 Javascript 对象

javascript - 使用ajax和php更新数据库

php - Jquery 自动完成与 mysql UTF8 不起作用

javascript - 正则表达式在括号内捕获时忽略括号