tags:

views:

122

answers:

6

I have a few strings in the following format:

S25 22.087 E152 46.125
S23 32.230 E148 10.576
S25 00.039 E152 12.480
S26 19.496 E152 43.501

I would like to parse the strings and split them into two parts, so: $foo = 'S25 22.087 E152 46.125';

would become:

$foo[0] = 'S25 22.087';
$foo[1] = 'E152 46.125';

(it doesn't have to be in an array, two new variables would also work fine).

How can this be done? I'd prefer to have a regexp use rather than finding the posing of E and doing a substr().

A: 

What about something like this :

$foo = 'S25 22.087 E152 46.125';
$m = array();
if (preg_match('/^(.*?)(E.*)$/', $foo, $m)) {
        var_dump($m);
}

The idea, here, being yo :

  • get everything from the beginning of the string, in non-greedy mode
  • to get everything that stars with the E, to the end of the string
  • the first match being non-greedy, it'll stop when the second match begins.

(Of course, there are plenty of other possible ways to do that -- like matching everything but E for the first part, for instance)


Which will get you :

array(3) {
  [0]=>
  string(22) "S25 22.087 E152 46.125"
  [1]=>
  string(11) "S25 22.087 "
  [2]=>
  string(11) "E152 46.125"
}

You then have to only use $m[1] and $m[2].

Note : you'll also have to use trim on the two strings, to ensure there is no white space at the begining or end of each one.

Pascal MARTIN
A: 

Try this regular expression:

/(S\d+ [\d.]+) (E\d+ [\d.]+)/
Gumbo
A: 
$foo = 'S25 22.087 E152 46.125';
preg_match_all('~[A-Z]\d+\s+[\d.]+~', $foo, $parts, PREG_SET_ORDER);
$parts = array_map('reset', $parts);
print_r($parts);
stereofrog
+2  A: 

S25 22.087 E152 46.125 to me looks like a latitude and longitude position value. So you should also expect N25 22.087 W152 46.125 and be able to parse that as well.

$foo = 'S25 22.087 E152 46.125';
$matches = array();
if (preg_match('/^([NS].*)\s([EW].*)$/', $foo, $matches)) {
 var_dump($matches); // $matches[1] = 'S25 22.087'; $matches[2] = 'E152 46.125'
}
Lukman
Do you by any chance know which of those 2 (S25 22.087 / E152 46.125) is the latitude and which is the longitude?
Click Upvote
North vs South is latitude, East vs West is longitude: http://en.wikipedia.org/wiki/Geographic_coordinate_system#Latitude_and_longitude
Lukman
+1  A: 

How about:

$foo = 'S25 22.087 E152 46.125';
$foo_parts = explode(' ', $foo);
$foo = array(implode(array($foo_parts[0], $foo_parts[1])), implode(array($foo_parts[2], $foo_parts[3])));

No regular expressions :)

Felix
where's your $foo_parts?
Corrected that, thanks.
Felix
A: 

If all those lines are the same length and same precision, simply do it like that:

$line = 'S25 22.087 E152 46.125';
$posH = substr( $line,  0, 10 );
$posV = substr( $line, 11, 11 );

That should be faster than any regexp approach.

poke