首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP str_pad 實現卡號/訂單號固定長度補零:高效生成規範編碼

     編輯:PHP 相關知識

PHP str_pad 實現卡號/訂單號固定長度補零:高效生成規範編碼

業務系統中常需生成固定長度的編碼:會員卡號、訂單號、員工工號、發票代碼等。str_pad() 是 PHP 內建的最佳工具,支援左右填充、自定義填充字符、長度控制。

函數語法

str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
常量行為示例
STR_PAD_LEFT左側填充 (補零常用)str_pad('1', 5, '0', STR_PAD_LEFT) → 00001
STR_PAD_RIGHT右側填充 (默認)str_pad('1', 5, '0', STR_PAD_RIGHT) → 10000
STR_PAD_BOTH兩側填充,右側優先str_pad('1', 5, '0', STR_PAD_BOTH) → 00100

核心應用:批量生成 10 位卡號

<?php
$cardCount = 10;
$cards = [];

for ($i = 1; $i <= $cardCount; $i++) {
    // 關鍵:STR_PAD_LEFT 實現左側補零
    $cards[] = str_pad((string)$i, 10, '0', STR_PAD_LEFT);
}

print_r($cards);
/*
Array
(
    [0] => 0000000001
    [1] => 0000000002
    [2] => 0000000003
    [3] => 0000000004
    [4] => 0000000005
    [5] => 0000000006
    [6] => 0000000007
    [7] => 0000000008
    [8] => 0000000009
    [9] => 0000000010
)
*/

進階封裝:通用編碼生成器

<?php
class CodeGenerator {
    public static function generate(
        int $sequence,
        int $length = 10,
        string $prefix = '',
        string $suffix = '',
        string $padChar = '0'
    ): string {
        if ($length < 1) throw new InvalidArgumentException('長度必須大於 0');
        if (mb_strlen($padChar) !== 1) throw new InvalidArgumentException('填充字符必須為單字符');

        $numStr = (string)$sequence;
        if (mb_strlen($numStr) > $length) {
            throw new OverflowException("序列號 $sequence 超過最大長度 $length");
        }

        $padded = str_pad($numStr, $length, $padChar, STR_PAD_LEFT);
        return $prefix . $padded . $suffix;
    }

    public static function batchGenerate(
        int $start,
        int $count,
        int $length = 10,
        string $prefix = '',
        string $suffix = ''
    ): array {
        $codes = [];
        for ($i = 0; $i < $count; $i++) {
            $codes[] = self::generate($start + $i, $length, $prefix, $suffix);
        }
        return $codes;
    }
}

// 使用示例
$cards = CodeGenerator::batchGenerate(1, 1000, 8, 'VIP', '');
// 生成:VIP00000001, VIP00000002, ..., VIP00001000

$orders = CodeGenerator::batchGenerate(10000, 500, 12, 'ORD-', '-CN');
// 生成:ORD-0000010000-CN, ORD-0000010001-CN, ...

常見業務場景對比

場景長度前綴填充字符示例
會員卡號10-16VIP/MC0VIP0000001234
訂單號12-18ORD/OD0ORD202401150001
員工工號6-8EMP/工0EMP000123
發票代碼10-12INV/發0INV0000000456
優惠券碼8-12COUPON0/A-ZCOUPON000ABC

效能優化:大批量生成

<?php
// 百萬級生成:避免循環調用函數開銷
function generateCodesVectorized(int $start, int $count, int $length, string $padChar = '0'): array {
    $format = "%0{$length}s"; // sprintf 格式化,比 str_pad 快 ~20%
    $codes = [];
    for ($i = 0; $i < $count; $i++) {
        $codes[] = sprintf($format, $start + $i);
    }
    return $codes;
}

// 基準測試 (100萬次)
$start = microtime(true);
$codes1 = [];
for ($i = 1; $i <= 1000000; $i++) {
    $codes1[] = str_pad((string)$i, 10, '0', STR_PAD_LEFT);
}
echo "str_pad: " . (microtime(true) - $start) . "s\n"; // ~0.45s

$start = microtime(true);
$codes2 = generateCodesVectorized(1, 1000000, 10);
echo "sprintf: " . (microtime(true) - $start) . "s\n"; // ~0.38s

避坑指南

  • ❌ 未檢查長度溢出:序列號位數超過目標長度時,str_pad 返回原字符串,導致長度不一致 → 必須驗證或截斷
  • ❌ 填充字符多字符:str_pad('1', 5, '00') 會重複 '00' 導致長度不可控 → 強制單字符
  • ❌ 浮點數序列號:str_pad(1.5, 5, '0') → 001.5 → 強制轉整數字符串
  • ✅ 併發安全:序列號來源需原子操作 (Redis INCR、數據庫自增、雪花算法)
  • ✅ 唯一性保證:生成後寫入數據庫唯一索引,捕獲衝突重試

擴展:字母數字混合編碼 (Base36)

<?php
function toBase36(int $num): string {
    $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $result = '';
    while ($num > 0) {
        $result = $chars[$num % 36] . $result;
        $num = (int)($num / 36);
    }
    return $result ?: '0';
}

function generateShortCode(int $seq, int $length = 8): string {
    $base36 = toBase36($seq);
    return str_pad($base36, $length, '0', STR_PAD_LEFT);
}

// 1000000 → 000LFLS (6位) vs 0000001000000 (13位),節省 54% 長度

str_pad 是生成固定長度編碼的標準工具。封裝通用生成器、處理邊界條件、考慮併發與效能,能構建穩定可靠的業務編碼系統。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved