Jump to content

remove whitespace to allow adding in php4


trauch

Recommended Posts

I put together a script that that will allow for the adding of a string of numbers in a txt file. However, I've got a problem since the numbers have spaces in place of commas (ie 2 345 instead of 2,345). This causes an obvious problem when adding. I am therefore trying to remove the spaces. I considered the trim commands but they dont address spaces in the middle of numbers.

 

I tried the str_replace command but it doesnt seem to work (or Im doing it wrong).

 

Can someone help me add to this script to remove the spaces to thereby allow for the adding?

 

 

<?php

$lines = file('textfile.txt/');

echo "sum($lines) = " . array_sum($lines) . "\n";

 

$lines = file('textfile.txt');

$sum = array_sum($lines);

$fp = fopen('total.txt', 'w');

fwrite($fp, $sum);

fclose($fp);

 

?>

Here is an example of the contents of the text file that Im trying to add and write to a new file. Please note that any number in the string over 999 incudes a space (ie 1 000)

 

1 007

2 000

3 000

4 001

 

When I use array_sum to add these numbers the total is "10" when it should be 10,008.

 

I've added the str_replace command before the sum command but it does not seem to work. The script that Im working with is below

 

<?php

 

$string = "string to replace all spaces";

$string = str_replace(" ","",$string);

 

$lines = file('textfile.txt/');

echo "sum($lines) = " . array_sum($lines) . "\n";

 

$lines = file('textfile.txt');

$sum = array_sum($lines);

$fp = fopen('total.txt', 'w');

fwrite($fp, $sum);

fclose($fp);

 

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.