Jump to content

Recommended Posts

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.

Link to comment
https://forums.phpfreaks.com/topic/268285-validate-numbers/
Share on other sites

You really should be using typecasting for this, as mentioned above.

 

That said, the problems you had with your second RegExp are as follows:

  1. [*]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.

Link to comment
https://forums.phpfreaks.com/topic/268285-validate-numbers/#findComment-1377343
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.