PHP如何从包含年月的字符串中提取数值并拼接为指定格式日期
提取月年逻辑实现方案
你可以通过正则匹配直接定位字符串中的月/年片段,代码如下:
foreach($files as $file){ $month = ""; $year = ""; // 提取逻辑开始 if (preg_match('/(\d{1,2})\/(\d{4})/', $file['expired_date'], $matches)) { // 捕获结果:$matches[1]为月份,$matches[2]为年份 $month = $matches[1]; $year = $matches[2]; // 可选:给单数字月份补前导零,统一日期格式 $month = str_pad($month, 2, '0', STR_PAD_LEFT); } // 提取逻辑结束 $new_expired_date = "15-$month-$year"; }
可选增强(合法范围校验)
如果你需要严格校验提取到的年月在你指定的范围内,可以调整为以下逻辑:
foreach($files as $file){ $allowYears = [2021, 2022, 2023, 2024, 2025, 2026]; $allowMonths = range(1, 12); $month = ""; $year = ""; if (preg_match('/(\d{1,2})\/(\d{4})/', $file['expired_date'], $matches)) { $tempMonth = (int)$matches[1]; $tempYear = (int)$matches[2]; if (in_array($tempYear, $allowYears) && in_array($tempMonth, $allowMonths)) { $month = str_pad((string)$tempMonth, 2, '0', STR_PAD_LEFT); $year = (string)$tempYear; } else { // 自定义非法日期处理逻辑,比如跳过、打日志等 continue; } } $new_expired_date = "15-$month-$year"; }
逻辑说明
- 正则
/(\d{1,2})\/(\d{4})/会自动匹配字符串中符合1-2位数字/4位数字规则的月年组合,不受前面的普通字符串干扰 - 补前导零的步骤可以按需保留,比如你需要输出
15-9-2020格式就可以删掉该步骤
内容的提问来源于stack exchange,提问作者dokohew
相关产品推荐
相关产品推荐

