Page 1 of 1

remove whitespace to allow adding in php4

Posted: Sat Dec 20, 2008 5:58 pm
by trauch
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);

?>

Re: remove whitespace to allow adding in php4

Posted: Sat Dec 20, 2008 6:48 pm
by jaoudestudios
Can you give examples of what result you have now and what result you want?

Do you want this "123 456" to convert this to "123465"?

Show us your attempt with str_replace

Re: remove whitespace to allow adding in php4

Posted: Sat Dec 20, 2008 8:24 pm
by trauch
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);

?>

Re: remove whitespace to allow adding in php4

Posted: Sun Dec 21, 2008 6:50 am
by jaoudestudios
Its because your $string is an array!

You will have to loop through the array and do str_replace for each element.

Use a foreach.