[英]PHP - How do you randomize the last 4 digits of a phone number
How would you randomize the last 4 digits of a phone number? 您将如何随机分配电话号码的后4位?
Given: 鉴于:
$phone = '000-000-0000';
Results would be: 结果将是:
$phone = '000-000-1943';
where 1943 is a random number 其中1943是随机数
Can this be done in a single line command using something like preg... 可以使用preg之类的命令在单行命令中完成...
or some other one line command ? 或其他一行命令?
substr
is good for extracting n characters from the beginning/end of string; substr
适合从字符串的开头/结尾提取n个字符; rand
can be used to generate a random number, sprintf
can be used to format a number. rand
可用于生成随机数, sprintf
可用于格式化数字。 Put all three functions together: 将所有三个功能放在一起:
$phone = '000-000-0000';
$phone = sprintf('%s%04d', substr($phone, 0, -4), rand(0, 9999));
echo $phone;
// 000-000-2317
$phone = preg_replace_callback('/\d{4}$/', function($m) {
return str_pad(mt_rand(0, 9999), 4, '0');
}, $phone);
$phone = '000-000-0000';
$phone=explode('-',$phone);
$phone[2]=str_pad(rand(0,9999), 4, 0);
$phone=implode('-', $phone);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.