I have a variable called $CARD_NUM
which can have any amount of numbers more than 4.
How can I replace all but the last 4 characters in this string with asterisks (*)?
For example if:
$CARD_NUM = '123456789012'
The resultant string should be:
********9012
If the variable is guaranteed to be at least 4 digits long, then
$CARD_NUM = "123456789012";
echo str_repeat('*', strlen($CARD_NUM) - 4) . substr($CARD_NUM, -4);
// or, as DougW suggested in a comment, if the string is NOT guaranteed to be at least 4 digits
// echo str_repeat('*', MAX(4, strlen($CARD_NUM)) - 4) . substr($CARD_NUM, -4);
should do it, see it in action!
Try this:
$CARD_NUM = "123456789012";
$replacement = '*';
echo preg_replace('/\d(?=\d{4})/m', $replacement, $CARD_NUM);
If you wanna view 2 or 3 digits only to be displayed just replace 4
in '/\d(?=\d{4})/m'
to whatever number of digits you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.