1

我目前有一个如下所示的文本文件:

Test1 = 120827 = December 23, 2012:
Test2 = 147203 = December 23, 2012:
Test3 = 11806 = December 23, 2012:
Test4 = 11806 = December 23, 2012:
Test5 = 0 = December 23, 2012:

我想要做的是将第二列中的所有数字加在一起。我怎样才能用 PHP 做到这一点?我的实际文件比这个大得多。

Test1 = *120827 = December 23, 2012:
Test2 = *147203 = December 23, 2012:
Test3 = *11806 = December 23, 2012:
Test4 = *11806 = December 23, 2012:
Test5 = *0 = December 23, 2012:

*我要补充的。

任何帮助将不胜感激!谢谢!

4

2 回答 2

1

PHP:

$sum = 0;
foreach (file($filename) as $line) {
   list(,,$num) = explode(' ', $line);
   $sum += $num;
}

如果文件太大,请使用fopen+fgets而不是file.

重击:

cut -d' ' -f3 filename | paste -sd+ | bc
于 2012-12-26T18:43:21.440 回答
0
<?php
$pattern = '/(?<=\=\s)([0-9]+)(?=\s\=)/';
$total = 0;
$matches;
$filename = "add.txt";
$handle = @fopen($filename, "r");

if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {        
        if(preg_match($pattern, $buffer, $matches))
        {
            $total += intval($matches[0]);  
        }       
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

?>
于 2012-12-26T18:58:32.913 回答