trauch Posted December 20, 2008 Share Posted December 20, 2008 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/137863-remove-whitespace-to-allow-adding-in-php4/ Share on other sites More sharing options...
.josh Posted December 21, 2008 Share Posted December 21, 2008 $string = "string to replace all spaces"; $string = str_replace(" ","",$string); Quote Link to comment https://forums.phpfreaks.com/topic/137863-remove-whitespace-to-allow-adding-in-php4/#findComment-720526 Share on other sites More sharing options...
trauch Posted December 21, 2008 Author Share Posted December 21, 2008 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/137863-remove-whitespace-to-allow-adding-in-php4/#findComment-720556 Share on other sites More sharing options...
redarrow Posted December 21, 2008 Share Posted December 21, 2008 Have you looked at number_format() function yet, try it. url number_format() function. http://uk3.php.net/number_format Quote Link to comment https://forums.phpfreaks.com/topic/137863-remove-whitespace-to-allow-adding-in-php4/#findComment-720654 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.