I need to extract strings from txt file example : <itrader="1" utrader="2334"> <itrader="2" utrader="5436"> <itrader="3" utrader="4326"> <itrader="4" utrader="9789"> <itrader="5" utrader="6388"> to : Itrader = 1 Utrader = 2334 Itrader = 2 Utrader = 5436 Itrader = 3 Utrader = 4326 Itrader = 4 Utrader = 9789 Itrader = 5 Utrader = 6388 Please help me with this
If your string data is always like your example, then this function is what you need. <?php # Here's the function function extract_data($string) { $string = str_replace('<', '', $string); $string = str_replace('>', '', $string); $string = str_replace('"', '', $string); $data = array(); $count = 0; $array1 = explode("\n", $string); foreach ($array1 as $item) { $array2 = explode(' ', $item); foreach ($array2 as $item2) { $array3 = explode('=', $item2); if (strlen(trim($array3[0]))>0) { $data[$count][trim($array3[0])] = trim($array3[1]); } } $count++; } return $data; } # This is how you use this function. $string = ' <itrader="1" utrader="2334"> <itrader="2" utrader="5436"> <itrader="3" utrader="4326"> <itrader="4" utrader="9789"> <itrader="5" utrader="6388"> '; $data = extract_data($string); # The result of the function is an array data # containing the itrader and utrader counts. print_r($data); ?> PHP:
Here's another method: <?php function extract_data($string) { preg_match_all('/<itrader="(\d+?)" utrader="(\d+?)">/', $string, $matches); foreach($matches[1] as $key => $value) $data[$value] = $matches[2][$key]; return $data; } ?> PHP:
If I were you, I would go with brendandonhue's method. Less code, and most likely a lot quicker to process.
You could also use array_combine() (I try to avoid loops whenever possible) function extract_data($string) { preg_match_all('/<itrader="(\d+?)" utrader="(\d+?)">/', $string, $matches); return array_combine($matches[1], $matches[2]); } PHP:
Unfortunately, lots of hosts are still using PHP4. IMO, may as well add 2 lines of code for the compatibility, IMO, but either way works.
I see your point. Though, I'm trying to make people upgrade first, and only if there's no way for them to upgrade, then I post the PHP 4 solution/change. I've been doing it like this for a while. Just doing my best trying to kill PHP 4.