remove whitespace to allow adding in php4

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
trauch
Forum Newbie
Posts: 14
Joined: Thu Dec 11, 2008 4:50 pm

remove whitespace to allow adding in php4

Post 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);

?>
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: remove whitespace to allow adding in php4

Post 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
trauch
Forum Newbie
Posts: 14
Joined: Thu Dec 11, 2008 4:50 pm

Re: remove whitespace to allow adding in php4

Post 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);

?>
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: remove whitespace to allow adding in php4

Post 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.
Post Reply