简体   繁体   中英

PHP: Read file into array

I have a large (~5MB) text file with a content similar to this:

> -L"FIR ANTANANARIVO"
55.5000001034   -19.0053549236
55.5000001034   -10.0053549152
55.5000001034   -19.0053549236
> -L"FIR ANTOFAGASTA"
-69.76998889    -17.96612222
-69.95860556    -18.24945
-80.2033334761  -18.35000067
> -L"FIR ASHGABAT"
61.3850333  38.655
60.2866333  39.8950333
56.4517 40.055

Data is shorted to three lines each for readability. Each data set can be longer than ~200 lines.

Using \\> -L\\".*\\" as matching string only returns the whole line and not the part in quotes only.

Desired output array:

Array
(
    [0] => Array
        (
            [0] => FIR ANTANANARIVO
            [1] => 55.5000001034    -19.0053549236
            [2] => 55.5000001034    -10.0053549152
            [3] => 55.5000001034    -19.0053549236
        )
    [1] => Array
        (
            [0] => FIR ANTOFAGASTA
            [1] => -69.76998889 -17.96612222
            [2] => -69.95860556 -18.24945
            [3] => -80.2033334761   -18.35000067
        )
    [2] => Array
        (
            [0] => FIR ASHGABAT
            [1] => 61.3850333   38.655
            [2] => 60.2866333   39.8950333
            [3] => 56.4517  40.055
        )
)

This is the code I'm currently using:

$firs = file_get_contents('data/firs.txt');
preg_match_all("/^\> -L\".*\"?(?=\n\>|\z)", $firs, $treffer);
print_r($treffer);

returns the whole line and not the part in quotes only .

You might forget to group it. Get it from matched group from index 1.

\> -L\"(.*)\"

Online demo


Try with Positive Lookbehind and Positive Lookahead . In that case there is no need to catch it from groups.

(?<=\> -L\").*(?=\")

Online demo


Get all the the desired values in matched groups from index 1.

 ((?<=\> -L\").*(?=\")|^-?\d.*$)

Online demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM