【PHP】价格区间字段验证,如4万-5万
参数值示例:
$str1 = "4万-5万";
$str2 = "4万-5万元";
$str3 = "5万元以内";
以下是一个PHP示例,用于检查字符串是否满足要求:
function checkString($str) {// 检查字符串中是否包含"-"或"以内"$containsHyphen = strpos($str, "-") !== false;$containsWithin = strpos($str, "以内") !== false;// 如果字符串中既不包含"-"也不包含"以内",则返回falseif (!$containsHyphen && !$containsWithin) {throw new Exception('价格区间中既不包含"-"也不包含"以内"');}// 正则:检查"以内"前面的字符是否为数字或"数字+万"或"数字+万元"或"数字+元"$numPattern = "/^\d+(?:\.\d{1,2})?(?:万|万元|元)?$/u";// 如果字符串中包含"-",则检查两侧是否为空if ($containsHyphen) {$parts = explode("-", $str);if (empty($parts[0]) || empty($parts[1])) {throw new Exception('价格区间检查"-"两侧错误 - 1');}// 检查"-"两侧的字符if (!preg_match($numPattern, $parts[0]) || !preg_match($numPattern, $parts[1])) {throw new Exception('价格区间检查"-"两侧错误 - 2');}}// 如果字符串中包含"以内",则检查前面的字符是否为数字或"万",后面是否为空if ($containsWithin) {$parts = explode("以内", $str);if (empty($parts[0]) || !empty($parts[1])) {throw new Exception('价格区间检查"以内"错误 - 1');}// 检查"以内"前面的字符if (!preg_match($numPattern, $parts[0])) {throw new Exception('价格区间检查"以内"错误 - 2');}}// 检查字符串中是否包含多个"-"或"以内"if (substr_count($str, "-") > 1 || substr_count($str, "以内") > 1) {throw new Exception('价格区间包含多个"-"或"以内"');}return true;
}// 测试示例
$str1 = "4万-5万";
$str2 = "4万以内";
$str3 = "4万-5万以内";
$str4 = "4万-以内";
$str5 = "4万-5万-6万";
$str6 = "4万以内5万";var_dump(checkString($str1)); // 输出:bool(true)
var_dump(checkString($str2)); // 输出:bool(true)
var_dump(checkString($str3)); // 输出:bool(false)
var_dump(checkString($str4)); // 输出:bool(false)
var_dump(checkString($str5)); // 输出:bool(false)
var_dump(checkString($str6)); // 输出:bool(false)