volatileboy Posted December 7, 2010 Share Posted December 7, 2010 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! Quote Link to comment https://forums.phpfreaks.com/topic/220956-regular-expression-help/ Share on other sites More sharing options...
salathe Posted December 7, 2010 Share Posted December 7, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/220956-regular-expression-help/#findComment-1144109 Share on other sites More sharing options...
volatileboy Posted December 7, 2010 Author Share Posted December 7, 2010 Thanks for your help, ill get on it =) Quote Link to comment https://forums.phpfreaks.com/topic/220956-regular-expression-help/#findComment-1144112 Share on other sites More sharing options...
volatileboy Posted December 7, 2010 Author Share Posted December 7, 2010 $pattern = '/[0-9]{1,3}\.[0-9]{6}/'; This pattern appears to work okay, glad to see I wasn't too far away! Quote Link to comment https://forums.phpfreaks.com/topic/220956-regular-expression-help/#findComment-1144117 Share on other sites More sharing options...
salathe Posted December 8, 2010 Share Posted December 8, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/220956-regular-expression-help/#findComment-1144330 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.