Jump to content

leading zero not allowed, regex


CrustyDOD

Recommended Posts

Hey

 

I want to show error when the input in field contains leading zero. Field should be integer and nothing else!

So for example, this types are not allowed:

- 0

- 00

- 01

- 094

and so on..

 

so far, i have this: eregi('^([0-9]{1,10})$', $d)..

 

Field must contain ONLY integers but do not allow leading zero!

 

Anyone can help?

Link to comment
Share on other sites

There are a number of ways to accomplish this.  If you don't have to use regular expressions, which is preferred due to (albeit minor) performance considerations, you can use ltrim($var,'0') to trim zeros from the left side (beginning) of the string.  You can use substr($var,0,1) == 0 to check if the first character is a zero.  If you are accepting user input, you'll have to check for other things, of course, like leading/trailing whitespace.

 

But a regex that will check for an integer sans leading zero(s):

 


preg_match('/^([1-9]\d*)/',$var,$match);
echo $match[1];

 

That pattern matches one digit from one through nine (not zero) at the beginning of the string, followed by none or some numeric digits.  You can constrain the amount of excess digits by changing the asterisk to {,10} for instance.  You can also leave off the caret (^) in case of leading whitespace, again, if you are accepting user input.

Link to comment
Share on other sites

Almost forgot about this :)

 

Right, maybe i wrote this in the wrong way. 0 is allowed to be after the first digit!

- 20

- 200162100

and so on..

 

All i want is that 0 is not in the first place but it can be anywhere else.

 

Yeah i know about other options i can use but if possible i would like to do this with regex..

Link to comment
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.