iversonm Posted December 14, 2009 Share Posted December 14, 2009 Hey I am sure this is easy enough but I have made my attempts and failed so I come to the Gods of Regex! I want to only allow numbers 0-9 and + - * / and ^ any advice would be appreciated Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/ Share on other sites More sharing options...
Daniel0 Posted December 14, 2009 Share Posted December 14, 2009 Right, so a number is -?[0-9]+. Either of the operators +, -, *, / and ^ require a number on both sides. preg_match('#^-?[0-9]+(?:[-+*/^](?:\(-[0-9]+\)|[0-9]+))*$', $string); So basically, you can do 1*2, but you can't do 1*-2 because it needs to be 1*(-2). I didn't test it very thoroughly, but I'm pretty sure it works. It can probably be optimized as well. Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/#findComment-977313 Share on other sites More sharing options...
iversonm Posted December 14, 2009 Author Share Posted December 14, 2009 No ending delimiter '#' found i have no idea what that means Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/#findComment-977316 Share on other sites More sharing options...
Daniel0 Posted December 14, 2009 Share Posted December 14, 2009 Sorry, make it preg_match('#^-?[0-9]+(?:[-+*/^](?:\(-[0-9]+\)|[0-9]+))*$#', $string); Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/#findComment-977317 Share on other sites More sharing options...
iversonm Posted December 14, 2009 Author Share Posted December 14, 2009 assuming preg_match('#^-?[0-9.]+(?:[-+*/^](?:\(-[0-9.]+\)|[0-9.]+))*$#', $string) works for decimals then topic solved. you are my hero Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/#findComment-977322 Share on other sites More sharing options...
Daniel0 Posted December 14, 2009 Share Posted December 14, 2009 Well, it will work for decimals, but it will also allow illegal things like this: 1.2.3.4.5.....7 You can do like this: preg_match('#^-?[0-9]+(?:\.[0-9])*(?:[-+*/^](?:\(-[0-9]+(?:\.[0-9])*\)|[0-9]+(?:\.[0-9])*))*$#', $string); (untested) Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/#findComment-977325 Share on other sites More sharing options...
iversonm Posted December 15, 2009 Author Share Posted December 15, 2009 So what would I need to add if I want to allow numbers after the decimal to be as long as i want so 1.1 is valid but 1.11 is not Quote Link to comment https://forums.phpfreaks.com/topic/185140-numbers-and-symbols/#findComment-977461 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.