Help me parse this file with PHP

2020-05-08 07:07发布

Fri Nov 27 10:00:01 EST 2009         974        12506
Fri Nov 27 11:00:01 EST 2009         988        12655
Fri Nov 27 12:00:01 EST 2009        1005        12886
Fri Nov 27 13:00:01 EST 2009        1026        13115
Fri Nov 27 14:00:01 EST 2009        1042        13429

I tried to explode on \n and then \t, but it looks like there are no tabs in the file...

标签: php parsing
4条回答
SAY GOODBYE
2楼-- · 2020-05-08 07:37

It appears to be fixed column width. You're going to need to either:

  • Use substr() and extract each column, then trim whitespace
  • Use preg_split() and look for two or more spaces in a row '/\s+/'
  • Other

Explode will likely return a bunch of empty elements, since it only matches a single character / one space.

查看更多
神经病院院长
3楼-- · 2020-05-08 07:44

This'll split at all whitespace collections, regardless of size.

$lines = file($myfile);
foreach ($lines as $line) {
    $line = preg_split('/\s+/', $line);
    # do stuff with line
}
查看更多
闹够了就滚
4楼-- · 2020-05-08 07:45
$lines = explode( "\r\n", $str );

foreach( $lines as $line){

echo 'date = ' .  substr( $line, 0 , 28) . PHP_EOL;
echo 'var1 =  ' . substr( $line, 28 , 12) . PHP_EOL;
echo 'var2 =  ' . substr( $line, 40 , 12) . PHP_EOL;
echo '
' ; }

If possible PHP treats all incoming vars as an integer first of all, so if the text files are of predictable length ( 24, 12, 12 Chars that I can see) then 0000000974 will be correctly parsed as being the integer 974 without having to resort to trim.

Isn't it alway best to aviod regexes if you can?

查看更多
相关推荐>>
5楼-- · 2020-05-08 08:01
$line = "Fri Nov 27 10:00:01 EST 2009         974        12506";
preg_match_all('~\S+~', $line, $parts);
print_r($parts[0]);

the rest is up to you

查看更多
登录 后发表回答