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? Link to comment https://forums.phpfreaks.com/topic/184925-preg_split/ 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); Link to comment https://forums.phpfreaks.com/topic/184925-preg_split/#findComment-976195 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 ]+/ Link to comment https://forums.phpfreaks.com/topic/184925-preg_split/#findComment-976209 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! Link to comment https://forums.phpfreaks.com/topic/184925-preg_split/#findComment-976233 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() Link to comment https://forums.phpfreaks.com/topic/184925-preg_split/#findComment-976369 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! Link to comment https://forums.phpfreaks.com/topic/184925-preg_split/#findComment-976488 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.