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
https://forums.phpfreaks.com/topic/220956-regular-expression-help/
Share on other sites

Have a read through http://php.net/regexp.reference.repetition as that seems to be where you're having most trouble.  After that, be sure to (re-)familiarise yourself with http://php.net/regexp.reference.anchors :)

 

Post back if you a) find a solution (sharing is caring) or b) still have trouble.

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.

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.