我使用
chunk_split()
在每第 4 个字母后添加一个“-”,但它也在字符串末尾添加一个,这是我不想要的,这是代码:
function GenerateKey($input)
{
$generated = strtoupper(md5($input).uniqid());
echo chunk_split(substr($generated, -24), 4, "-");
}
这可能不是生成序列密钥的最有效方法。我认为如果我使用
mt_rand()
会更好,但现在就这样了。
那么我该如何让它不在字符串末尾添加“-”呢? 因为现在输出看起来像这样:
89E0-1E2E-1875-3F63-6DA1-1532-
您可以通过 rtrim 删除试用。试试这个
$str = "89E01E2E18753F636DA11532";
echo rtrim(chunk_split($str,4,"-"), "-");
输出:
89E0-1E2E-1875-3F63-6DA1-1532
我建议不要添加稍后必须删除的字符。
chunk_split()
和 wordwrap()
将不必要地添加尾随连字符。
相反,使用更直接的方法,在每第 4 个字符(不是字符串末尾)后面的零宽度位置插入连字符。
代码:(演示)
echo preg_replace('/.{4}\K(?!$)/', '-', $yourGeneratedString);
# .{4} #four characters
# \K #forget the previously matched characters
# (?!$) #only qualify the match for replacement (injection) if not the end of the string