haillucker haillucker - 3 months ago 7
PHP Question

How to show only the last 4 degits of a creditcard

'xx' is a number ( credit card number with 16 number ) i need to show only the last 4 degits, someone can help me please

example :

xx = 9999999999991234

(value='9999999999991234') = (value='***********1234')


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

Answer

You can use preg_replace() for such operations like so:

    $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)

As a function:

<?php

    function getTruncatedCCNumber($ccNum){
        $last4Digits    = preg_replace( "#(.*?)(\d{4})$#", "$2", $ccNum);
        $firstDigits    = preg_replace( "#(.*?)(\d{4})$#", "$1", $ccNum);
        return preg_replace("#(\d)#", "*", $firstDigits) . $last4Digits;
    }

    $ccNum          = "9999999999991234";
    var_dump(getTruncatedCCNumber($ccNum));
    // PRODUCES::::   string '************1234' (length=16)

To display this in a div, do like so:

<?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>
Comments