PHP在数字逻辑中设置最小4位数

时间:2015-08-15 02:46:44

标签: php regex number-formatting

我是PHP的新手,我正在尝试在变量中设置最小4位数字并创建一个memberid。

$memberidVal = ABC0123;
$numMemberVal = preg_replace("/[^0-9]/", "", $memberidVal);
if (strlen($numMemberVal) == 3) {
    $numMemberVal = 0 . $numMemberVal;
} elseif (strlen($numMemberVal) == 2) {
    $numMemberVal = 00 . $numMemberVal;
} elseif (strlen($numMemberVal) == 1) {
    $numMemberVal = 000 . $numMemberVal;
}
$newMemberId = "ABC" . ($numMemberVal + 1);
echo ($newMemberId);

无论我做什么,我总是得到ABC124作为回报。

1 个答案:

答案 0 :(得分:1)

$newMemberId = "ABC" . ($numMemberVal + 1);

以上一行正在执行以下操作:

  1. 使用数字字符串0123并将小数点1添加到124,感谢type juggling
  2. 然后它是在“ABC”前面,因为你告诉它
  3. 如果您想强制使用前导零使用str_pad()

    $memberidVal = ABC0123;
    $numMemberVal = preg_replace("/[^0-9]/", "", $memberidVal);
    $newMemberId = "ABC" . str_pad(($numMemberVal + 1), 4, '0', STR_PAD_LEFT);
    

    或者在添加{0}之前添加1

    $memberidVal = ABC0123;
    $numMemberVal = preg_replace("/[^0-9]/", "", $memberidVal);
    $numMemberVal++;
    if (strlen($numMemberVal) == 3) {
        $numMemberVal = 0 . $numMemberVal;
    } elseif (strlen($numMemberVal) == 2) {
        $numMemberVal = 00 . $numMemberVal;
    } elseif (strlen($numMemberVal) == 1) {
        $numMemberVal = 000 . $numMemberVal;
    }
    $newMemberId = "ABC" . $numMemberVal;
    echo ($newMemberId);
    

    或使用sprintf()

    $memberidVal = ABC0123;
    $numMemberVal = preg_replace("/[^0-9]/", "", $memberidVal);
    $newMemberId = sprintf('%s%04d', 'ABC', ($numMemberVal + 1));