PHP: Negative Numbers and ctype_digit
Question by Compi | 2016-06-07 at 21:09
In one of my PHP scripts, I get some data from an HTML form and before processing the input, I would like to check whether there is really an integer number submitted.
Up to now, I have used the PHP function ctype_digit() for that. This is working quite well as long as the number or digit is positive. However, now I would also like to allow negative numbers and ctype_digit() always returns false for them.
What can I do to validate both, positive and negative numbers?
Related Topics
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
Negative Ratings with Reason
Blog | 1 Comment
HTML Form: Redirection depending on Radiobutton or Checkbox State
Tutorial | 0 Comments
PHP: Current Date and Time
Tutorial | 0 Comments
Lazarus: Input of binary, hexadecimal and integer numbers
Article | 0 Comments
Delphi/Lazarus: Only allow Numbers in TEdit
Tip | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Using ctype_digit(), you can only test whether the passed string is consisting of digits (0-9). The function does not check whether the string is holding a valid integer number that can possibly be negative.
However, you can use this regular expression and preg_match() for your purpose:
This if statement with this regular expression ensures:
So, with this code, you can identify negative as well as positive numbers of an arbitrary length.
2016-06-08 at 20:12