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!

 

 

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

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];

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.