-1

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 ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Sammy
  • 877
  • 1
  • 10
  • 23
  • @Michael Berkowski I am not assigning phone numbers. It is actually used to assign a random part number that looks similar to a phone number. The phone number format is an analogy that is easier to understand for this question. – Sammy Jan 08 '13 at 12:55

4 Answers4

6

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
Salman A
  • 262,204
  • 82
  • 430
  • 521
4
$phone = preg_replace_callback('/\d{4}$/', function($m) {
    return str_pad(mt_rand(0, 9999), 4, '0');
}, $phone);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2

You could use the rand method together with the str_pad method.

$phone = '000-000-'.str_pad(rand(0,9999), 4, '0');
Hugo Delsing
  • 13,803
  • 5
  • 45
  • 72
0
$phone = '000-000-0000';
$phone=explode('-',$phone);
$phone[2]=str_pad(rand(0,9999), 4, 0);
$phone=implode('-', $phone);
enrey
  • 1,621
  • 1
  • 15
  • 29