Lirong Zuo
Lirong Zuo

Reputation: 45

separate a string from some specific words in php

I have a string called $metar

 $metar = EICK 011300Z 10004KT 27/17 Q1018 TEMPO AT0800 20006KT 010V220 9999 SCT029

and this string could changed every an hour depending a dynamic file.

in basic, i want to separate the $metar to two strings, the separate point is "AT0800"

list($a, $b) = explode(' AT0800 ', $metar);
echo $b;

but the problem is the "AT0800" could change to "AT1200" or "AT1900" in the future, the only words are keep is the "AT", So how can i get the string $b which is after the word "ATxxxx" ? Thanks

Upvotes: 1

Views: 104

Answers (3)

sjagr
sjagr

Reputation: 16502

Split the string with AT#### using a regex:

$metar_split = preg_split('/AT[0-9]{4}/', $metar);

The first half:

echo trim($metar_split[0]);

The second half (the one you're looking for):

$b = trim($metar_split[1]);

To get the AT#### portion:

preg_match('/AT[0-9]{4}/', $metar, $matches);
$metar_at = $matches[0];

Upvotes: 3

Lirong Zuo
Lirong Zuo

Reputation: 45

here you go, the answer is attached below:

       list($a, $b) = explode('AT', $metar, 2);
        //echo $b;
        list($c, $d) = explode(' ', $b, 2);
        //echo $d;

Upvotes: 0

Gabor
Gabor

Reputation: 560

If the position of ATxxxx in the string is always fixed (and the number of characters before it are also fixed), and xxxx always means 4 digits, then you could just go and use substr to select the desired segment of the string, as in:

$part1 = substr($metar, 0, 38);
$part2 = substr($metar, 46);

However, if you are looking at a varying lengths for the rest of the content, yet ATxxxx format is expected, you could have at it with a regular expression along the lines of:

([\w\s\/]+) AT[0-9]{4} ([\w\s\/]+)

This will grab out your two parts, which are seperated by the letters AT and exactly 4 digits. The [\w\s\/]+ part says: "grab me word characters (letters and numbers), white spaces and slash characters at least one, or any number more".

Upvotes: 0

Related Questions