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
}
:) 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