我是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作为回报。
答案 0 :(得分:1)
$newMemberId = "ABC" . ($numMemberVal + 1);
以上一行正在执行以下操作:
0123
并将小数点1
添加到124
,感谢type juggling 如果您想强制使用前导零使用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));