Function accepts credit card number as string parameter and formats it by adding "-" hyphen after every 4 characters.
Function
function formatCreditCard($cc) {
$cc = str_replace(array('-', ' '), '', $cc);
$cc_length = strlen($cc);
$newCreditCard = substr($cc, -4);
for ($i = $cc_length - 5; $i >= 0; $i--) {
if ((($i + 1) - $cc_length) % 4 == 0)
$newCreditCard = '-' . $newCreditCard;
$newCreditCard = $cc[$i] . $newCreditCard;
}
return $newCreditCard;
}
Calling The Function
$string = '5555222299997777'; echo formatCreditCard($string);
Output
5555-2222-9999-7777

Leave A comment
Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *