Jump to content

Regular Expression help!


volatileboy

Recommended Posts

Hey guys I am not very experienced with regular expressions, nor do I understand the syntax very well, I am trying to write a pattern to validate a longitude or latitude value, the valid formats would be:

 

123.123456

12.123456

1.123456

 

So basically a 1 or 3 digit number, followed by a period, followed by 6 numbers 0-9, the pattern I came up with is below but it does not seem to work propperly:

 

$pattern = '/^[0-9]{3}\.[0-9]{1}/';

 

I hope someone can assist me, thanks for reading!

Link to comment
Share on other sites

Great (and thanks for taking the time to figure it out!). Just be aware that, because the regex is not anchored (see my previous post), it will match against strings containing anything on either side of what your pattern is matching.  If you want to make sure that a string contains only the lat/lon number, then you must anchor the pattern.

 

For example:

 

$subject = 'test 123.456789 string';

$pattern = '/[0-9]{1,3}\.[0-9]{6}/';
if (preg_match($pattern, $subject)) {
    echo "Unanchored pattern matched against '$subject'\n";
}

$pattern = '/^[0-9]{1,3}\.[0-9]{6}$/';
if (preg_match($pattern, $subject)) {
    echo "Anchored pattern matched against '$subject'\n";
}

 

Finally, this may or may not be a problem but, your regex will allow numbers like 001.234567.

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.