How to split a file separated by space?

I am trying to import this:

http://en.wikipedia.org/wiki/List_of_countries_by_continent_%28data_file%29

which has the format:

AS AF AFG 004 Afghanistan, Islamic Republic of
EU AX ALA 248 Åland Islands
EU AL ALB 008 Albania, Republic of
AF DZ DZA 012 Algeria, People Democratic Republic of
OC AS ASM 016 American Samoa
EU AD AND 020 Andorra, Principality of
AF AO AGO 024 Angola, Republic of
NA AI AIA 660 Anguilla

if i do

<? explode(" ",$data"); ?>

which works great except for countries with more than 1 word.

how can i split it to get the first 4 bits of data (chars / ints) and the 5th bit of data will remain something else?

this is in php

Thank you

+3
source share
4 answers

The function explodeaccepts an optional limit parameter. Change the function call to:

<?php explode(" ", $data, 5); ?>

and you will get the name of the country as the last element in the array containing spaces.

+11
source

Using unpack :

$format = "A2cont/x/A2alpha2/x/A3alpha3/x/A3num/x/a*eng";
$line = "AS AF AFG 004 Afghanistan, Islamic Republic of";
$ar = unpack($format, $line);

He produces:

array (
  'cont' => 'AS',
  'alpha2' => 'AF',
  'alpha3' => 'AFG',
  'num' => '004',
  'eng' => 'Afghanistan, Islamic Republic of',
)

( ) , .

+3

You can use preg_match and your text will be in $match[5];

<?php
$str = 'AS AF AFG 004 Afghanistan, Islamic Republic of';
$chars = preg_match('/([A-Z]*)\ ([A-Z]*)\ ([A-Z]*)\ ([0-9]*)\ (.*)\ /', $str, $match);
print_r($match);
?>
0
source

Perhaps sscanf can also do what you need:

<?php
// in my example I loaded the data in an array line by line
$lines = file('sscanf_data.txt');

foreach($lines as $line) {
    $data = array();
    // define the format of the input string, assign the 
    // extracted data to an associative array
    sscanf($line, "%s %s %s %s %[^.]", 
        $data['col_1'], 
        $data['col_2'], 
        $data['col_3'], 
        $data['col_4'], 
        $data['col_5']);

    // dump array contents
    print_r($data);
}

Conclusion:

Array
(
    [col_1] => AS
    [col_2] => AF
    [col_3] => AFG
    [col_4] => 004
    [col_5] => Afghanistan, Islamic Republic of

)
...

It's good that if you store data in an associative array, you already have pairs of field values ​​for inserting them into the database.

0
source

Source: https://habr.com/ru/post/1750062/


All Articles