Generating a random number complying a specific pattern
I want to generate a number that contains 14 digits. But I want to generate it in a certain pattern. Consider t开发者_JAVA百科he following number:
292 0505 150 0253
- The bold numbers are constants
0505
is a day and a month meaning05
is the month and05
is the day. So when generating the random number the first part must be from0
to12
and the second one from1
to31
- The other number (
150
) is random
I want each attempt post to a page by curl.
Now, if I understood correctly what you want, try this:
$numberAsString = '292' . mt_rand(1, 12) . mt_rand(1, 31) . mt_rand(0, 9) . mt_rand(0, 9) . mt_rand(0, 9) . '0253';
I saved the number as a string because I don't think PHP may handle numbers that large without using floats.
function randomNumber($startDate,$endDate){
$days = round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24));
$n = rand(0,$days);
return '292'.date("md",strtotime("$startDate + $n days")).rand(100,999).'0253';
}
$myRandomNumber = randomNumber('2010-01-01', '2010-12-31');
$url = "http://www.example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $myRandomNumber);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
This is assuming you are POSTing the data. If using GET (or another HTTP method) then changes will be needed.
You can give a date range you want to include for the first 4 random numbers (for example to allow for including / excluding leap years - or to keep the date before today)
If I understand you correctly:
positions 1-4 random 0000-9999
positions 5,6 (starting with the rightmost) random 01-12
positions 7,8 range 01-31
positions 9-14 random 000000-999999
I dont know whats you backend, but php format is rand (min,max)
You can merge numbers as 14-character-long string, using sprintf on positions 5,6 and 7,8 to ensure leading zero for single-digit date.
32-bit php will not support 14-decimal digits in either int or float. But it does not look like you need to do any math operations on this long number.
Convolution & confusion all around.
echo '292'
.DateTime::createFromFormat('z',rand(0,365))->format('md')
.sprintf('%03d',rand(0,999))
.'0253';
Which has the added advantage of not throwing the 000-099 randomness away as the accepted answer does.
精彩评论