Nodral Posted September 12, 2012 Share Posted September 12, 2012 Hi All I'm a bit of a newbie to regex and am struggling with what seems like the most basic preg_replace. I need to validate numbers and remove anything non-numeric from a string. ie 4.5volts would become 4.5 -67 degrees would be -67 I have this preg_replace('/[^.-0-9]/', '', $aValue['value']); however there can only be one minus and it must be at the start, and there can only be one decimal point. Any help is much appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/268285-validate-numbers/ Share on other sites More sharing options...
Nodral Posted September 12, 2012 Author Share Posted September 12, 2012 I now have preg_match('[-\+]?\b[0-9]+(\.[0-9]+)?\b', $value['value'], $match); However I am getting error preg_match() [function.preg-match]: Unknown modifier '?' in..... Come on guys, I really need this one!! lol Quote Link to comment https://forums.phpfreaks.com/topic/268285-validate-numbers/#findComment-1377198 Share on other sites More sharing options...
scootstah Posted September 12, 2012 Share Posted September 12, 2012 Can't you just use typecasting? <?php $i = '-65.55asdfasdfasdf'; echo (int) $i; // -65 echo (float) $i; // -65.55 Quote Link to comment https://forums.phpfreaks.com/topic/268285-validate-numbers/#findComment-1377204 Share on other sites More sharing options...
Jessica Posted September 12, 2012 Share Posted September 12, 2012 For more: http://us2.php.net/manual/en/language.types.type-juggling.php Quote Link to comment https://forums.phpfreaks.com/topic/268285-validate-numbers/#findComment-1377212 Share on other sites More sharing options...
Christian F. Posted September 12, 2012 Share Posted September 12, 2012 You really should be using typecasting for this, as mentioned above. That said, the problems you had with your second RegExp are as follows: [*]Missing delimiters, which causes the RegExp engine to assume that the opening [ is a delimiter. Thus the error. [*]Use of word boundaries. Especially in between the notation sign and the value. You don't need the word boundaries at all, as the + is a greedy modifier and you've asked it to match digits only. Also, you could have used \\d instead of [0-9] to tell the RegExp engine that you wanted a digit. Quote Link to comment https://forums.phpfreaks.com/topic/268285-validate-numbers/#findComment-1377343 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.