I have credit card number which I want to mask as below:
$cc = 1234123412341234
echo cc_masking($cc)
1234XXXXXXXX1234
function cc_masking($number) {.....}
<?php
echo 'XXXX-XXXX-XXXX-'.substr($cc,-4);
?>
You can use substr_replace
$var = '1234123412341234';
$var = substr_replace($var, str_repeat("X", 8), 4, 8);
echo $var;
Output
1234XXXXXXXX1234
This should work using substr
:
function ccMasking($number, $maskingCharacter = 'X') {
return substr($number, 0, 4) . str_repeat($maskingCharacter, strlen($number) - 8) . substr($number, -4);
}
Not the elegant way but it works
<?php
$cc = "1234123412341234";
function cc_masking($number) {
$int_first = 4;
$int_last = 4;
$chars = strlen($number);
$repeater = "x";
$repeates = $chars-$int_first-$int_last;
// echo "<p>Org: $number</p>";
$mask = substr($number,0,4).str_repeat($repeater,$repeates).substr($cc,-4);
// echo "<p>Mask: $mask";
return $mask;
}
echo cc_masking($cc);
?>
I was looking for some code similar. So I found the code below. I hope can help.
function mask($val, $mask)
{
$maskared = '';
$k = 0;
for ($i = 0; $i <= strlen($mask) - 1; $i++) {
if ($mask[$i] == '#') {
if (isset($val[$k]))
$maskared .= $val[$k++];
} else {
if (isset($mask[$i]))
$maskared .= $mask[$i];
}
}
return $maskared;
}
Sample:
echo mask(11111111111, "###.###.###-##"); // 111.111.111-11
echo mask(11111111111, "#####-###"); // 111111-111
echo mask(11111111111, anything); // 111111-111
My 5 cents.
Examples:
371449635398431 => XXX-XXXX-XXXX-8431
4111111111111111 => XXXX-XXXX-XXXX-1111
public function maskCreditCardNumber($cc, $maskFrom = 0, $maskTo = 4, $maskChar = 'X', $maskSpacer = '-')
{
// Clean out
$cc = str_replace(array('-', ' '), '', $cc);
$ccLength = strlen($cc);
// Mask CC number
if (empty($maskFrom) && $maskTo == $ccLength) {
$cc = str_repeat($maskChar, $ccLength);
} else {
$cc = substr($cc, 0, $maskFrom) . str_repeat($maskChar, $ccLength - $maskFrom - $maskTo) . substr($cc, -1 * $maskTo);
}
// Format
if ($ccLength > 4) {
$newCreditCard = substr($cc, -4);
for ($i = $ccLength - 5; $i >= 0; $i--) {
// If on the fourth character add the mask char
if ((($i + 1) - $ccLength) % 4 == 0) {
$newCreditCard = $maskSpacer . $newCreditCard;
}
// Add the current character to the new credit card
$newCreditCard = $cc[$i] . $newCreditCard;
}
} else {
$newCreditCard = $cc;
}
return $newCreditCard;
}