Jesper
Jesper

Reputation: 422

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-

Upvotes: 3

Views: 800

Answers (3)

mickmackusa
mickmackusa

Reputation: 47991

I recommend not adding characters which will have to be removed later.

chunk_split() will needlessly add a trailing hyphen, but wordwrap() won't. Demo

echo wordwrap($yourString, 4, '-', true);

The regex equivalent is to insert hyphens at the zero-width position after every 4th character which is not the end of the string.

Code: (Demo)

echo preg_replace('/.{4}\K(?!$)/', '-', $yourString);

    # .{4}      #four characters
    # \K        #forget the previously matched characters
    # (?!$)     #only qualify the match for replacement (injection) if not the end of the string

A less direct approach is to explode between each four characters then implode with hyphens. Demo

echo implode('-', str_split($yourString, 4));

Upvotes: 0

MH2K9
MH2K9

Reputation: 12039

You can remove the trialing - by rtrim. Try this

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

Output:

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

Upvotes: 3

jh314
jh314

Reputation: 27802

You can chop off the - with rtrim():

echo rtrim(chunk_split(substr($generated, -24), 4, "-"), "-");

Upvotes: 0

Related Questions