0

The spec says to check for a non-negative integer in buy.php by using preg_match("/^\d+$/", $_POST["shares"]). I've tried to understand this expression and have gotten most of it, but would like some help on two points.

  1. Can someone break apart the regex search string for me? I'm not sure that I really follow it.
  2. How is this better than using is_int($_POST["shares"])?

Thanks!

1
  • regex101.com I pasted in your regex and it returned this handy dandy explanation: ^\d+$/ ^ assert position at start of the string \d+ match a digit [0-9] Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] $ assert position at end of the string edited comment about a dozen times, learning this minimarkdown. – Celebrity Butter Churner Oct 1 '15 at 5:15
3

Let's break it down:

preg_match("/^\d+$/", $_POST["shares"])

I think you can tell that $_POST["shares"] is the variable to be mached and the regex string is /^\d+$/.

The first and last / are the delimiters of the regex, so we are left with ^\d+$.

  • ^ assert start of subject (or line, in multiline mode)

So that marks the beginning of the regex.

  • \d any decimal digit

So that tells that a digit should follow (in fact it should start with a digit and not with a - for example). So even though you might think that +4 is a positive integer, this preg_match() would not think so, because it doesn't start with a decimal digit.

  • + 1 or more quantifier

So you can in fact have "one ore more" decimal digits. So at least one decimal digits are needed one after another.

  • $ assert end of subject or before a terminating newline (or end of line, in multiline mode)

And that marks the end of the regex string.

So all that means that for the given string to be a positive int, it has to start with a decimal digit, that can be possible followed by other decimal digits, but nothing more.

If you want to learn more, check the PHP documentation about preg_match() and more specifically the meta characters of the PCRE regex and the escape sequences of PCRE regex.


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

2
  • Just one clarification in regards to the second part of the question. Is the difference then that is_int could accept a hex value as an int or is there some other difference? – reddisht Oct 1 '15 at 13:25
  • 1
    Nevermind. is_int checks for ints but not for negatives or 0s. – reddisht Oct 1 '15 at 16:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .