繁体   English   中英

如何与PHP一起在文本文件中添加数字?

[英]How to add numbers in a text file together with 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:

我想做的是将第二列中的所有数字加在一起。 我该如何使用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:

*我要添加的内容。

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

PHP:

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

如果文件太大,请使用fopen + fgets代替file

BASH:

cut -d' ' -f3 filename | paste -sd+ | bc
<?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);
}

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM