Manitoba
Manitoba

Reputation: 8702

Format a string as a serial number

I'd like to format a string into a serial number. I'd like to get something like that: AAAAA-BBBBB-CCCCC-DDDDD with alpha-numeric characters (0-9ABCDEF).

So far, I've tried to create a regex to achieve that but I don't know exactly how I am supposed to deal with that. Here is the code I made:

$output = preg_replace('[0-9ABCDEF]{5}[0-9ABCDEF]{5}[0-9ABCDEF]{5}[0-9ABCDEF]{5}', '$1-$2-$3-$4', $input);

It's pretty basic but I can't make it works.

$input contains a raw string; For example A47D2F771AC412BADC4F (20 chars long).

Thanks in advance for your precious help.

Upvotes: 1

Views: 641

Answers (2)

Anthony
Anthony

Reputation: 37065

Try this non regex approach and save yourself a headache:

$pieces = str_split( $input, 5 );

$formatted_input = implode("-", $pieces);

Upvotes: 3

kennytm
kennytm

Reputation: 523494

You forgot the groups.

 preg_replace('([0-9A-F]{5})([0-9A-F]{5})([0-9A-F]{5})([0-9A-F]{5})', ...
#              ^           ^^           ^^           ^^           ^

Upvotes: 3

Related Questions