简体   繁体   English

你如何在php中用星号替换除最后4个字符之外的所有字符

[英]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.

相关问题 如何用星号替换某些字符 - How To Replace Some Characters With Asterisks 如何在php中替换除下划线和句点之外的所有特殊字符? - how to replace all special characters except underscore and period in php? PHP删除之前的所有字符,除了最后一个数字 - PHP remove all characters before, except last number 如何从PHP字符串中替换除数字(200、200.45等)以外的所有字符? - How to replace all characters except a numeral (200, 200.45 etc.) from a string in php? 无法理解如何将除给定序列以外的所有字符与php中的preg_replace()进行匹配 - unable to understand how to match all characters except a given sequence with preg_replace() in php 如何用PHP中的已定义字符替换字符串中的所有数字? - How do you replace all numbers in a string with a defined character in PHP? 如何用星号替换php中的最后4位数字以外的手机号码 - How to replace the mobile number with stars except last 4 digits in php 如何制作 jQuery 或 WordPress PHP 计算字符然后找到最后一个空格并用“...”替换所有内容 - How to make jQuery or WordPress PHP that counts characters then finds last space and replace all content after with “…” 替换除第一个和空格以外的所有字符 - Replace all characters except first one and whitespaces Preg替换除+之外的所有非数字字符 - Preg Replace all non numerical characters except +
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM