You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现序列号日期提取:基于序列号确定产品保修日期

Parse Serial Number to Get Warranty Start Date

Got it, let's work through this problem together. You need to extract a warranty start date (formatted as YYYY-MM-01) from serial numbers like 217A111111111, where:

  • The second and third digits (e.g., 17 in 217A...) represent the last two digits of the year (so 17 → 2017)
  • The fourth character is the month code: 1-9 map to January-September, A=October, B=November, C=December

Here's a step-by-step solution using regex plus simple mapping logic:

Step 1: Use Regex to Capture Key Components

First, we'll write a regex to grab the year suffix and month code from the start of the serial number. The pattern ^\d(\d{2})([1-9ABC]) works here:

  • ^ anchors to the start of the string
  • \d matches the first irrelevant digit (like the 2 in 217A...)
  • (\d{2}) captures the 2-digit year suffix (first group)
  • ([1-9ABC]) captures the month code (second group, matches allowed characters)

Step 2: Convert Captured Values to Date Format

Once we have the two captured groups, we can transform them into the required date string:

  1. Year: Prepend 20 to the 2-digit suffix (e.g., 17 → 2017)
  2. Month: Use a mapping dictionary to convert the code to a 2-digit month number:
    • For digits 1-9, pad with a leading zero (e.g., 1 → 01)
    • For letters, map A→10, B→11, C→12

Example Code (Python)

import re

def get_warranty_date(serial_number):
    # Define regex pattern and month mapping
    pattern = r'^\d(\d{2})([1-9ABC])'
    month_map = {'A': '10', 'B': '11', 'C': '12'}
    
    # Match the pattern
    match = re.match(pattern, serial_number)
    if not match:
        return None  # Handle invalid serial numbers
    
    year_suffix, month_code = match.groups()
    
    # Build year string
    year = f"20{year_suffix}"
    
    # Build month string
    if month_code.isdigit():
        month = month_code.zfill(2)
    else:
        month = month_map.get(month_code)
    
    # Combine into YYYY-MM-01 format
    return f"{year}-{month}-01"

# Test cases
print(get_warranty_date("217A111111111"))  # Output: 2017-10-01
print(get_warranty_date("217111111111"))   # Output: 2017-01-01
print(get_warranty_date("320B999999999"))  # Output: 2020-11-01

How It Works

  • The regex ensures we only extract valid components from the start of the serial number
  • The month mapping handles both digit and letter codes cleanly
  • We pad single-digit months with a leading zero to maintain the MM format requirement
  • The function returns None for serial numbers that don't match the pattern, making it easy to handle invalid inputs

内容的提问来源于stack exchange,提问作者Marz_89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:13:22