Jump to content

[SOLVED] List of data


Recommended Posts

I have a huge list of words in a txt. I was wondering is their a way of formatting it?


The list is like:




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:




Is their a way to do this?, if so would you mind, providing an example please.



Link to comment
Share on other sites

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)




$fileContents = file('filename.txt');
foreach ($fileContents as $lineNum => $line)
   $portions = explode (':', $line);
   $swapped[$portions[1]] = $portions[0];



Hope that helps. Hope I got it all right. Code untested.

Link to comment
Share on other sites

You could use preg_replace():


$data = file_get_contents('filename.txt');
$data = preg_replace('~^([^:]*).*?)$~m', '$2:$1', $data);


Or my approach using file():


$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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • 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.