Jump to content

Need help with using regular expressions in PHP please...


teamv

Recommended Posts

I'm using an API to return co-ordinates of a postcode I gave it. Here is the result:

 

$georesult = "map.centerAndZoom(new GPoint(-1.5234513, 53.432567), 4)";

 

I have built a regular expression to extract the individual co-ordinates:

 

-\d*[\.\d,\s]*

 

Which matches "-1.565323, 53.811008", and I was then planning to explode the string using ", " as the delimiter to extract the individual co-ordinates. However I'm having trouble using the regualr expressions functions preg_match and preg_split. I just seem to be going round in circles I just don't quite undertsand how I am supposed to use them, and deal with their output/data structure.

 

Could anyone advise me on what/how I call the correct preg (or another type of) function to extract the text with the delimeter provided please? Would be greatly appreicated. Thanks!

 

 

You can use preg_match_all to get all of the coordinates. The first (and only) array contains the full pattern matches.

 

<pre>
<?php
$georesult = "map.centerAndZoom(new GPoint(-1.5234513, 53.432567), 4)";
// The minus sign and leading digits are optional.
preg_match_all('/-?(?:\d+)?\.\d+/', $georesult, $matches);
print_r($matches);
?>
</pre>

As shown by print_r, $matches[0] is an array (the array of full pattern matches):

Array

(

    [ 0 ] => Array

        (

            ...

        )

)

The first match is going to be $matches[0][0]. Since this is only array you're accessing, you can simply it like so:

$matches = $matches[0];
echo $matches[0];

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.