Jump to content

[SOLVED] List of data


newbtophp

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:

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

Link to comment
https://forums.phpfreaks.com/topic/170977-solved-list-of-data/
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)

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.

Link to comment
https://forums.phpfreaks.com/topic/170977-solved-list-of-data/#findComment-901774
Share on other sites

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;
}
?>

Link to comment
https://forums.phpfreaks.com/topic/170977-solved-list-of-data/#findComment-901783
Share on other sites

Archived

This topic is now archived and is closed to further replies.

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