正则表达式匹配价格字符串

I am new in PHP. I was trying to check if one of the form inputs (contained in $price for this example) is a decimal as follows:

if(!preg_match("\\d+(.\\d{1,2})?", $price))
    //do something

In Java, it would have been

price.matches("\\d+(.\\d{1,2})?")

But the same regex is not working in PHP. Does preg_match match substrings as well?

I expect the following inputs to be true:

300
300.5
300.56

All other formats should be false. I cannot figure out how to do that in PHP.

Let's do this right:

is_string($price) and trim($price); // Might be worth doing first
if(preg_match('~^\\d+(?:\\.\\d{1,2})?$~', $price)) {
   $price = floatval($price); // Kewl, keep going
}else{
   // Unkewl, fail
}
  1. Wrap RegExp in ~ character. Any non-reserved character works as a wrapper and / is terrible when dealing with URLs or HTML as you need to escape it too. It's a nightmare.
  2. Force the string to exact match by enclosing in ^ and $ and not a contain match like all these variants here.
  3. Wrap string in single quotes if you don't have PHP "{$variables}" that need to be expanded in them.
  4. Escape \ even in single quoted string like this \d or \.!
  5. Don't capture the block, it does not matter anyway but is a performance thing.

:) Rant done!

(!preg_match("/\d(\.\d{1,2})?/",$price))

Remember the starting and ending /'s

I don't understand how that could possibly have worked in Java. The first number only matches a single digit. Your examples match several digits.

Try this regex instead:

/\d+(?:\.\d{1,2})?/

Notice how I've put the regex inside a "wrapper" (the /) and notice how I removed your escaping of \ in front of the number matches. Also I replaced the capture group around your decimals with a non-capture group, because in your context it did not look like you would need it.

PHP code:

if (!preg_match("/\d+(?:\.\d{1,2})?/",$price)) {
    // do something
}

I would say

\d(\.\d{1,2})?

As far as I rememer a dot needs to be escaped as well