[英]How do you replace all characters except last 4 with asterisks in php
I have a variable called $CARD_NUM
which can have any amount of numbers more than 4.我有一个名为
$CARD_NUM
的变量,它可以包含超过 4 的任意数量的数字。
How can I replace all but the last 4 characters in this string with asterisks (*)?如何用星号 (*) 替换此字符串中除最后 4 个字符之外的所有字符?
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如果保证变量至少有 4 位长,那么
$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.如果您只想查看 2 或 3 位数字,只需将
'/\d(?=\d{4})/m'
中的4
替换为您想要的任何位数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.