php - How to split characters with "-" character? -
i generated serial number php, length of serial number 16 characters, want split serial number in 4 characters dash(-) character, format xxxx-xxxx-xxxx-xxxx wrote php code:
for ($d=0; $d<=3; $d++){ $tmp .= ($tmp ? "-" : null).substr($serial,$d,4); }
so loop return serial number xxxx-xxxx-xxxx-xxxx format,
i want know there better way or function in php?
i searched in internet found sprintf
, number_format
don't know how can use function format !
i use str_split()
, implode()
:
$result = implode( '-', str_split( $serial, 4));
str_split()
break string array, each element has 4 characters. then, implode()
joins array pieces dash.
so, if generate random $serial
with:
$serial = substr(md5(uniqid(rand(), true)), 0, 16);
we as output similar to:
59e6-997f-8446-80a2
Comments
Post a Comment