Jump to content

Inserting dashes into serial number


ivoilic

Recommended Posts

So I have this function which generates a random serial # that is 12 characters long.  However I want to insert a dash  every four characters like so: XXXX-XXXX-XXXX

Any suggestions?

 

<?php
$serial1 = get_serial_num(12);

//Serial # function		
function get_serial_num($number_cnt){
$ret_arr = array();
$serial = "";
$ser_num = array("1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
for($i = 0; $i < $number_cnt; $i++){
   $rand = rand(0,count($ser_num)-1);
   $val = wordwrap($ser_num[$rand],1,"\n", true);
   $serial .= $val;
   
}
return $serial;
}			
echo ''.$serial1.'';	
?>

 

Warning: I am a bit noobish.

Link to comment
Share on other sites

range is a very clean way to make an array using a range of characters.

array_merge will allow you to combine two arrays, made with range.

 

$ser_num = array_merge( range(0,9), range('A'-'Z') );

 

This is actually slower than hard coding it like you've done, but it also allows you to specify a customizable range of characters, if needed.

 

In your rand calculation, you count the size of $ser_num every time. This isn't necessary, and slows down your script quite a bit. Define a variable outside the loop, and use it in your rand() call.

$size = count($ser_num) - 1;

And in the loop

$rand = rand(0, $size);

 

Why are you using the wordwrap function? It seems to add no purpose, other than to add a line break after each character. If that's desired, you can simply write

$val = $ser_num[$rand] . "\n";

 

The fullstop/period/dot is a concatenation operator. It allows you to combine multiple values into a single one.

 

Finally, you probably want to use substr. It will return a given 'slice' of your string.

 

$value = 'ABCDEFGHIJKL';

$with_dashes = substr($value,0,4).'-'.substr($value,4,4).'-'.substr($value,;

echo $with_dashes;

 

With substr(), the first argument is the string to slice, the second is the starting offset (where to start the slice) and the third is length. More details about the kinds of values it will accept are in the manual. It's a very versatile and handy function

Link to comment
Share on other sites

One line of code (without indentiation) to create the serial.

 

print
  implode('-',                // concatenate each group with '-'
    str_split(                // split them into lenghts of 4
      implode('',             // concatenate them to a string
        array_rand(           // pick out 12 elements
          array_flip(         // array_rand reads keys, not values
            array_merge(      // merge ranges
              range(0, 9),    // 0 - 9
              range('A', 'Z') // A - Z
            )
          ),
        12)
      ),
    4)
  );

Link to comment
Share on other sites

There's a slight difference. His function allows for duplicate

 

$l = 15; // length of 'serial'
$h = 5; // where to place the 'hyphen'
$d = '-'; // the desired 'hyphen' symbol
$s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; // strings to chose from

for($i=0,$o='',$c=strlen($s)-1;$i<$l;$i++ )
$o.= $s[mt_rand(0,$c-1)].($i%$h==$h-1&&$i!=$l-1?$d:'');

echo $o;

 

Something you'd want to run into when trying to follow other people's code.

 

 

Link to comment
Share on other sites

You may still use your own logic or adapt the solutions offered by the above two.

From regular expression point of view, This may help.

$result = preg_replace('/^([\w]{4})([\w]{4})([\w]{4})$/sim', '\1-\2-\3', $subject);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.