简体   繁体   中英

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?

Given:

$phone = '000-000-0000';

Results would be:

$phone = '000-000-1943';

where 1943 is a random number

Can this be done in a single line command using something like preg...

or some other one line command ?

substr is good for extracting n characters from the beginning/end of string; rand can be used to generate a random number, sprintf can be used to format a number. 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);

您可以将rand方法与str_pad方法一起使用。

$phone = '000-000-'.str_pad(rand(0,9999), 4, '0');
$phone = '000-000-0000';
$phone=explode('-',$phone);
$phone[2]=str_pad(rand(0,9999), 4, 0);
$phone=implode('-', $phone);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM