如何只显示信用卡的最后4位数字


How to show only the last 4 degits of a creditcard

'xx'是一个数字(信用卡号码有16个数字),我只需要显示最后4位数字,有人可以帮助我,请

示例:xx = 9999999999991234(value='9999999999991234') = (value='***********1234')

<li>
    <div class="sectionValue" id='xxxxxxxx' value='<?echo $xx; ?>' </div>
</li>

您可以简单地使用substr()str_replace()的组合

<?php
    function getTruncatedCCNumber($ccNum){
        return str_replace(range(0,9), "*", substr($ccNum, 0, -4)) .  substr($ccNum, -4);
    }
?>
 <div class="sectionValue" id='account_changed' > 
     <?php echo getTruncatedCCNumber($ccNum); ?> 
 </div>

或者使用非高效的preg_replace():

    $ccNum          = "9999999999991234";
    $last4Digits    = preg_replace( "#(.*?)('d{4})$#", "$2", $ccNum);
    $firstDigits    = preg_replace( "#(.*?)('d{4})$#", "$1", $ccNum);
    $ccX            = preg_replace("#('d)#", "*", $firstDigits);
    $ccX           .= $last4Digits;
    var_dump($firstDigits);    //<== '999999999999' (length=12)
    var_dump($last4Digits);    //<== '1234' (length=4)
    var_dump($ccX);            //<== '************1234' (length=16)

要在div中显示此内容,请这样做:

<?php
    $ccNum          = "9999999999991234";
    function getTruncatedCCNumber($ccNum){
        $last4Digits    = preg_replace( "#(.*?)('d{4})$#", "$2", $ccNum);
        $firstDigits    = preg_replace( "#(.*?)('d{4})$#", "$1", $ccNum);
        return preg_replace("#('d)#", "*", $firstDigits) . $last4Digits;
    }
?>
 <div class="sectionValue" id='account_changed' > 
     <?php echo getTruncatedCCNumber($ccNum); ?> 
 </div>

使用stbstr的负值从右侧开始

<?php
$var = '1234567890';
echo '***********' . substr($var,-4);
?>

与其他响应类似,但封装在函数中我在php端准备了这个解决方案,因为这将更安全,不会将CC信息暴露给客户端(javascript)。

function ccMask($cc, $fillChar='*'){
    $last4= substr(str_replace(['-',' '],'',$cc), -4);
    return str_pad($last4, 16, $fillChar, STR_PAD_LEFT);
}
echo ccMask($cc);
echo ccMask($cc, '#');//you can pass in a different character if you like
echo ccMask('5421 5678 9012 9876', '#');//output ############9876

此方法还允许您传入带有或不带有连字符或空格的信用卡号

不要在家里尝试这些

value = '9999999999991234';
// convert string to array
var array = value.split("");
// define the new string
var newValue = '';
// loop through the array
for (var i = 0; i < array.length; i++) {
  if(i<12) {
    // for the first 12 digits add a 'x'
    newValue += 'x';
  } else {
    // for the last 4 digits add the digit
    newValue += array[i];
  }
}

更好的方法:PHP

<?php
$value = '9999999999991234';
$array = str_split($value);
$newValue = '';
for ($i=0; $i < ; $i++) {
  if(i<12) {
    // for the first 12 digits add a 'x'
    $newValue .= 'x';
  } else {
    // for the last 4 digits add the digit
    $newValue +. array[i];
  }
}
echo '(value=' . $newValue . ')';

如果你想回显HTML中的变量:

<div><? echo $newValue; ?></div>