PHP如何验证搜索输入的字符串是月份、年份还是日期?
你现有实现的核心问题
strtotime() 的默认行为会对用户输入中缺失的日期部分,自动填充当前系统时间的对应值,完全无法区分用户实际输入的内容粒度——比如输入纯October,函数会返回当前年份当前日期的十月时间戳,和输入October 5 2024得到的结构化解析结果没有差异,根本无法触发“纯月份搜索就返回所有十月内容”的业务逻辑。
正确的实现思路
判定用户输入的检索粒度,核心原则是先匹配原始输入的内容特征,再配合时间解析补全结构化参数,绝对不能仅靠strtotime()的解析结果反推用户意图。
具体分三层判定逻辑:
- 先识别纯内容粒度的输入:纯年份、纯月份,这类输入不需要依赖时间解析函数
- 再识别组合形式的输入:月份+年份、日+月份、完整年月日
- 最后将命中的检索参数对应到具体的检索规则上
可落地的示例代码
// 建立月份映射表,支持全称、常用缩写,不区分大小写 $monthMap = [ 'january' => 1, 'jan' => 1, 'february' => 2, 'feb' => 2, 'march' => 3, 'mar' => 3, 'april' => 4, 'apr' => 4, 'may' => 5, 'june' => 6, 'jun' => 6, 'july' => 7, 'jul' => 7, 'august' => 8, 'aug' => 8, 'september' => 9, 'sep' => 9, 'sept' => 9, 'october' => 10, 'oct' => 10, 'november' => 11, 'nov' => 11, 'december' => 12, 'dec' => 12 ]; // 预处理输入:去除首尾空格、统一转小写适配匹配规则 $searchInput = strtolower(trim($searchString)); $searchScope = null; $searchConditions = []; // 1. 判定纯年份输入:匹配1900-2099范围的4位数字 if (preg_match('/^(19|20)\d{2}$/', $searchInput)) { $searchScope = 'only_year'; $searchConditions = ['year' => (int)$searchInput]; } // 2. 判定纯月份输入:完全匹配映射表中的月份名/缩写 else if (isset($monthMap[$searchInput])) { $searchScope = 'only_month'; $searchConditions = ['month' => $monthMap[$searchInput]]; } // 3. 判定组合输入场景 else { $timestamp = strtotime($searchInput); // 排除无法解析为时间的输入 if ($timestamp !== false) { // 从原始输入中提取月份参数 foreach ($monthMap as $monthName => $monthNum) { if (strpos($searchInput, $monthName) !== false) { $searchConditions['month'] = $monthNum; break; } } // 从原始输入中提取年份参数 if (preg_match('/(19|20)\d{2}/', $searchInput, $yearMatch)) { $searchConditions['year'] = (int)$yearMatch[0]; } // 从原始输入中提取日参数(避开年份数字的干扰) if (preg_match('/\b(0?[1-9]|[12][0-9]|3[01])\b/', $searchInput, $dayMatch) && !preg_match('/^(19|20)\d{2}$/', $dayMatch[0])) { $searchConditions['day'] = (int)$dayMatch[0]; } // 基于实际提取到的参数确定检索范围 if (isset($searchConditions['year']) && isset($searchConditions['month']) && !isset($searchConditions['day'])) { $searchScope = 'year_month'; } else if (count($searchConditions) === 3) { $searchScope = 'full_date'; } } } // 后续根据$searchScope和$searchConditions拼接检索逻辑即可 // 比如检索范围为only_month时,仅匹配内容字段的月份为对应值,不限制年份和日期
注意事项
- 所有粒度判定必须基于用户输入的原始字符串,不要把
strtotime()自动补全的当前时间参数当成用户的检索条件,否则纯搜索October时会被错误限定为当前年份的十月内容 - 纯年份的匹配一定要加范围限制,避免把普通数字检索错误识别为日期搜索
- 月份匹配需支持大小写不敏感、缩写兼容,适配不同用户的输入习惯
内容的提问来源于stack exchange,提问作者nas
相关产品推荐
相关产品推荐

