Page 1 of 1

How to rewrite a list of text with PHP

Posted: Tue Jan 17, 2012 7:08 am
by lovelf
Hello, I have a list composed of text, it is an airports list, see below:

Maan Jordan JO Maan MPQ

That's an example taken from the list, the first word is the city, the second one is the country, the third one is the country abbreviation, the fourth one is the airport name, and the fifth one is the 3 characters airport iata code.

I would like to open up this txt file and read line to line to rewrite it with a different composition, I would like to turn that line to:

Maan, Jordan - Maan (MPQ)

So I would need code to open up the txt file, read line by line, break down by space into variables and check for a strlen of 2 to delete the airport abbreviation from the list, replace the abbreviation with a "-" actually, add parenthesis to the iata code, and add a comma after the city name. Sounds simple but I can't get it going.

Thanks.

Re: How to rewrite a list of text with PHP

Posted: Tue Jan 17, 2012 7:12 am
by Celauran
explode() should make easy work of this.

Re: How to rewrite a list of text with PHP

Posted: Tue Jan 17, 2012 3:01 pm
by Tiancris
Something like this? (not tested, so take it with caution!) :P

Code: Select all

$list = file('list.txt'); // read file
$new_list = array();
foreach ($list as $line) {
  $array_line = explode(' ', $line); // split by spaces
  $new_list[] = $array_line[0].', '.$array_line[1].' - '.$array_line[3].' ('.$array_line[4].')'; // make a line with desired format
}
file_put_contents ('new_list.txt' , $new_list); // write a new file
I used file() and file_put_contents() to simplify, you may want to use fopen(), fread(), fwrite() and fclose().