newbtophp Posted August 19, 2009 Share Posted August 19, 2009 I have a huge list of words in a txt. I was wondering is their a way of formatting it? The list is like: someone:something hello:bye Its all separated by ":" with no spaces. I was wondering if I can the formatting of the list using php so it looks like: The list is like: something:someone bye:hello Is their a way to do this?, if so would you mind, providing an example please. Thanks Quote Link to comment Share on other sites More sharing options...
Catfish Posted August 19, 2009 Share Posted August 19, 2009 Short answer: use file(), foreach and explode(). Long answer: Read the file to an array using function: file() Loop through said array (foreach) , during each loop, split the value on character : using function explode() and save the exploded parts to a new associative array placing the first portion in the value and the second portion in the key. File example: (filename.txt) test:value name:person <?php $fileContents = file('filename.txt'); print_r($fileContents); foreach ($fileContents as $lineNum => $line) { $portions = explode (':', $line); $swapped[$portions[1]] = $portions[0]; } print("\n\n"); print_r($swapped); ?> Hope that helps. Hope I got it all right. Code untested. Quote Link to comment Share on other sites More sharing options...
newbtophp Posted August 19, 2009 Author Share Posted August 19, 2009 Thanks for the answer its close, but the result is not how I'd like it . The results turn out like: [test:ok] Quote Link to comment Share on other sites More sharing options...
thebadbad Posted August 19, 2009 Share Posted August 19, 2009 You could use preg_replace(): <?php $data = file_get_contents('filename.txt'); $data = preg_replace('~^([^:]*).*?)$~m', '$2:$1', $data); ?> Or my approach using file(): <?php $data_arr = file('filename.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $data = ''; foreach ($data_arr as $line) { $data .= implode(':', array_reverse(explode(':', $line, 2))) . PHP_EOL; } ?> Quote Link to comment Share on other sites More sharing options...
newbtophp Posted August 19, 2009 Author Share Posted August 19, 2009 Thanks it worked 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.