PHP将命令“mailq”的输出转换为数组

时间:2013-01-17 13:13:52

标签: php regex linux arrays postfix-mta

我在执行命令mailq时遇到问题,并将其输出转换为多维数组中的值。

$results = array();

    exec('/usr/bin/mailq', $mailQresult);
    foreach ($mailQresult as $key => $mailqLine) {

        $res = preg_match('/^([A-Z0-9]{1,20})\s+([1-9][0-9]*)\s+((Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+[A-Za-z]{3}\s+[0-9]{2}\s+[0-9]{2}\:[0-9]{2}\:[0-9]{2})\s*$/', $mailqLine, $matches);
        if ($res) {
        // Insert message ID and other data into the object.
        // It will be competed afterwards.
        $mailqArray = array(
            'id' => $matches[1],
            'size' => intval($matches[2]),
            'date' => strftime($matches[3]),
            'sender' => $matches[5],
            'failed' => false,
            'recipients' => $matches[4]
            );
        }
    } 

mailq的输出包括空格并返回,看起来有点像这样:

ID    SIZE DAYNAME MONTH DAY HOUR:MINUTES:SECONDS  sender@address.com [new line here]
(Host or domain name not found. Name service error for name=address.com type=MX: Host not found, try again) [new line here]
recipient@address.com

因此错误消息和收件人以不同的键结束。

我知道我可以使用shell_exec将mailq的输出作为一个字符串获取,但我不知道如何编写将创建多维数组的正则表达式。

我可能正在接近这个错误。非常欢迎任何建议!

1 个答案:

答案 0 :(得分:0)

您可以检查数组中的下一个项目,看它是否包含新的messageid和其他指标。可能是for循环而不是foreach。