lindm Posted December 12, 2009 Share Posted December 12, 2009 I have the following code extract data from a text file: $contents = file("textfile.txt"); //chose file foreach($contents as $line_value) { list($cat, $int, $id, $num) = preg_split("/(\t| )/",$line_value); $cat = str_replace('#', '', $cat); $number[$cat][$int][$id]= trim($num); } The text file contents normally looks like this: #RES -1 6922 144897.52 #RES -1 6970 16894.59 #RES -1 6981 1110.00 #RES -1 6993 500.00 echo $number["RES"][-1][6981]; would return 1110.00 All fine. Now I have a text file where the whitespace varies like this: #RES -1 6922 144897.52 #RES -1 6970 16894.59 #RES -1 6981 1110.00 #RES -1 6993 500.00 echo $number["RES"][-1][6981]; would then return 0 which I of course don't want. Any easy way to solve this? Quote Link to comment Share on other sites More sharing options...
.josh Posted December 12, 2009 Share Posted December 12, 2009 $contents = file_get_contents("textfile.txt"); //chose file preg_match_all('~(0-9.]+)$~',$contents,$data); print_r($data); Quote Link to comment Share on other sites More sharing options...
salathe Posted December 12, 2009 Share Posted December 12, 2009 Or you could just split, as you were before, but with /[\t ]+/ Quote Link to comment Share on other sites More sharing options...
lindm Posted December 12, 2009 Author Share Posted December 12, 2009 Crayon Violent: Seems preg_match_all requires a string. salathe: Suggestion seems to work fine! Thanks all! Quote Link to comment Share on other sites More sharing options...
.josh Posted December 13, 2009 Share Posted December 13, 2009 Crayon Violent: Seems preg_match_all requires a string. salathe: Suggestion seems to work fine! Thanks all! that's why i changed your file() to file_get_contents() Quote Link to comment Share on other sites More sharing options...
lindm Posted December 13, 2009 Author Share Posted December 13, 2009 Now I see! My mistake. Good solution! Quote Link to comment 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.