Jump to content

white space in array from text file


Kane250

Recommended Posts

This is probably the dumbest question, but how can I get rid of all whitespace from an array I am creating from a text file?  I have numbers in a text file, separated by , and at the ends of some lines, I have done a soft return because my text editor does weird stuff with indenting when I don't.  However, when these numbers are pulled through later on, there is a space before some of the numbers.

 

Here is what I have been trying to use.  Doesn't work.  Any help is very much appreciated!

 

$numbers = file_get_contents('sample.txt');
$numbers = str_replace("\r\n","",$numbers); 
$numbers = explode(",", $numbers);

Link to comment
https://forums.phpfreaks.com/topic/163608-white-space-in-array-from-text-file/
Share on other sites

If there would only be space at the beginning and end after exploding into an array, then why else would I be getting white space in the middle of it?  That's my main problem.  The white space is coming from the soft returns in my list of numbers.

 

ex:

 

345,876,987

922, 761

 

When echoed from the array, the numbers would look like this:  345,876,987, 0922,761.  Notice the space?

Something like:

$numbers = array_map('trim', explode(',', $numbers);

or

$numbers = explode(',', trim($numbers));

 

Ok, that totally worked, ha. I used the first one:  $numbers = array_map('trim', explode(',', $numbers)); and it fixed it.  I still don't totally get it, but hey, great!  Thanks for your help!

Well, if each array element holds a string of separated values like 111,222,33, 456 and not one single number per array item, just do a str_replace(" ", "", $arrayelement) in a loop.

 

Thanks for the suggestion.  That's what I was originally doing and it was not removing it, which s why I was so confused.  Those numbers were single numbers separated by the , .  Anyway the solution above worked out, bu thanks for helping out.

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.