我有一个php脚本在我的Windows机器上运行cmd命令,我将标准输出从命令shell重定向回我的php脚本,我得到以下结果:
接收的接口统计信息已发送字节30750280 8480324
单播数据包44928 43160
非单播数据包0 0
丢弃0 0
错误0 0
未知协议0
我想要做的是使用RegEx格式化结果,以便我可以以表格形式输出数据,如:
interface statistics
received| 3535353535
sent | 4664646646
errors | 0
按顺序。
到目前为止,我只是尝试只格式化包含"字节"使用下面的代码没有太多运气;
if (preg_match('/Bytes/',$lines)) {
$lines = trim($lines);
$pieces = preg_split("/[\s,]+/", $lines);
echo $lines;
echo "Sent: ".(int)$pieces[1]."Reeived: ".$pieces[2];
preg_match_all('/(\d)|(\w)/', $lines, $matches);
$numbers = implode($matches[1]);
$letters = implode($matches[2]);
//var_dump($numbers, $letters);
//echo $numbers;
//echo $letters."letters";
}
答案 0 :(得分:0)
代码:(PHP Demo)(Pattern Demo)
$shell_output='Interface Statistics Received Sent Bytes 30750280 8480324
Unicast packets 44928 43160
Non-unicast packets 0 0
Discards 0 0
Errors 0 0
Unknown protocols 0';
$pattern='/Interface Statistics Received Sent Bytes (\d+) (\d+).*Errors (\d+).*/s';
$replace="interface statistics\nreceived| $1\nsent\t| $2\nerrors\t| $3";
echo preg_replace($pattern,$replace,$shell_output);
输出:
interface statistics
received| 30750280
sent | 8480324
errors | 0
该模式使用Interface Statistics Received Sent Bytes
上的文字匹配来减少步数。模式末尾的s
修饰符/标志将允许.
(点=任意字符)匹配换行符。该模式旨在用新的替换文本替换整个文本。