phpstringdelimiter

Insert hyphen after every n characters without adding a hyphen at the end


I'm using chunk_split() to add a "-" after every 4th letter, but it also add one at the end of the string, which I don't want, here's the code:

function GenerateKey($input)
{
    $generated = strtoupper(md5($input).uniqid());
    echo chunk_split(substr($generated, -24), 4, "-");
}

This may not be the most efficient way to generate a serial key. I think it would be better if I used mt_rand(), but it'll do for now.

So how would I so it doesn't add a "-" at the end of the string? Because right now the output looks like this:

89E0-1E2E-1875-3F63-6DA1-1532-


Solution

  • You can remove the trialing - by rtrim. Try this

    $str = "89E01E2E18753F636DA11532";
    echo rtrim(chunk_split($str,4,"-"), "-");
    

    Output:

    89E0-1E2E-1875-3F63-6DA1-1532