在PHP中使用preg_split进行JSON拆分

时间:2013-09-09 05:44:24

标签: php preg-split

我有不同的服务器

$strarrServerIp = array('192.168.123.1','192.168.123.2');
$strarrLogsData = array();
foreach($strarrServerIp as $strServerIp ){
       $strCommand = 'ssh abose@' . $strServerIp . ' cat /srv/www/vhosts/trunk/Logs/Log20130825.psi.log';
        $strarrLogsData[] = shell_exec( $strCommand );

            }
foreach( $strarrLogsData as $strJsonLogData ){
           foreach( preg_split("/((\r?\n)|(\r\n?))/", $strJsonLogData ) as $strJsonLineLog ) {
                                display($strJsonLineLog);
                        }
                }

服务器包含以这种形式包含JSON日志的文件。

 {"timestamp":"2013-08-25 20:35:06 MDT","severity":"INFO","data":"1"}
 {"timestamp":"2013-08-25 20:36:06 MDT","severity":"INFO","data":"15"}
 {"timestamp":"2013-08-25 20:37:06 MDT","severity":"INFO","data":"32"}
 {"timestamp":"2013-08-25 20:38:06 MDT","severity":"INFO","data":"25"}
 {"timestamp":"2013-08-25 20:39:06 MDT","severity":"INFO","data":"5"}

我想将它们分成一个数组

array (
    [0] => {"timestamp":"2013-08-25 20:35:06 MDT","severity":"INFO","data":"1"}
    [1] => {"timestamp":"2013-08-25 20:36:06 MDT","severity":"INFO","data":"15"}
    [2] => {"timestamp":"2013-08-25 20:37:06 MDT","severity":"INFO","data":"32"}
    [3] => {"timestamp":"2013-08-25 20:38:06 MDT","severity":"INFO","data":"25"}
    [4] => {"timestamp":"2013-08-25 20:39:06 MDT","severity":"INFO","data":"5"}
)

有什么建议吗? 我想要比

更好的东西
 preg_split("/((\r?\n)|(\r\n?))/", $strJsonLogData )

2 个答案:

答案 0 :(得分:1)

试试这个,你也可以使用file()函数来获取数组中的每一行。

$text = '
 {"timestamp":"2013-08-25 20:35:06 MDT","severity":"INFO","data":"1"} {"timestamp":"2013-08-25 20:36:06 MDT","severity":"INFO","data":"15"}
 {"timestamp":"2013-08-25 20:37:06 MDT","severity":"INFO","data":"32"}
 {"timestamp":"2013-08-25 20:38:06 MDT","severity":"INFO","data":"25"}
 {"timestamp":"2013-08-25 20:39:06 MDT","severity":"INFO","data":"5"}';

$array =  preg_split("#}.*?{#s", $text );

$array = array_map("trim", $array);
print_r($array);


//using preg_match_all

preg_match_all("#({.*?})#s", $text, $matches);
print_r($matches[1]);

答案 1 :(得分:0)

\n拆分,并在每一行使用json_decode