如何使用PHP preg_match函数验证符合指定规则的分数?
How to Validate Fractions in PHP with
preg_match (2 Decimal Places, Leading Digit Required) Got it, let's tackle this validation problem with PHP's preg_match function. Here's a straightforward solution that checks all your boxes:
function validateFraction($input) { // Regex pattern enforcing all your rules $validationPattern = '/^\d+\.\d{2}$/'; // preg_match returns 1 for a match, 0 for no match, false on error return preg_match($validationPattern, $input) === 1; } // Test the function with various cases var_dump(validateFraction("5.09")); // bool(true) (your valid example) var_dump(validateFraction("12.34")); // bool(true) (valid with multi-digit whole number) var_dump(validateFraction("0.99")); // bool(true) (valid with leading zero) var_dump(validateFraction(".78")); // bool(false) (no digit before decimal) var_dump(validateFraction("9.")); // bool(false) (no decimal digits) var_dump(validateFraction("8.1")); // bool(false) (only one decimal place) var_dump(validateFraction("abc.12")); // bool(false) (non-numeric characters)
Let's break down the regex pattern /^\d+\.\d{2}$/
Each part directly maps to your requirements:
^and$: These anchors ensure the entire string matches the pattern (no extra characters before or after the number)\d+: Matches one or more digits before the decimal point—this enforces your rule that there's at least one digit here\.: Escaped decimal point (since.is a special regex character that matches any character)\d{2}: Matches exactly two digits after the decimal point—this guarantees only two decimal places are allowed
This function will reliably return true for valid fractions and false for anything that violates your rules.
内容的提问来源于stack exchange,提问作者Kelvin Soohoo
相关产品推荐
相关产品推荐

