PHP Function for Generating Random Number & Random Digits placeholder.

While developing a SMS sending Tool, we wanted to provide the developers to use placeholders such as.

{{random_number_7}} or {{random_string_8}}
When these placeholders will be used in the bulk SMS sending program they will be replaced by a random number of 7 digits and random string of 8 digits respectively.

Behind the scene we had to create PHP functions which will pick up the test such as the following for the SMS to be sent.

SMS example.
Dear {{Username}}, your entry code is : {{random_string_5}}.
And your OTP : {{random_number_6}}

Now to automatically replace these place holders I build the following function with the help of preg_replace.

Function to Replace Random Numbers.

<?php
function replace_num_callback($matches) 
{
  return rand(pow(10, $matches[1]-1), pow(10, $matches[1])-1);
}
$input = "Dear {{Username}}, your entry code is :  {{random_string_5}}. 
And your OTP : {{random_number_6}}";
$pattern = '/\{\{random_number_(.*?)\}\}/i';
$result = preg_replace_callback($pattern, 'replace_num_callback', $input);
echo $result;
?>

Replacing the Random Strings.

<?php

function randomString($n) { 
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $randomString = ''; 
  
    for ($i = 0; $i < $n; $i++) { 
        $index = rand(0, strlen($characters) - 1); 
        $randomString .= $characters[$index]; 
    } 
  
    return $randomString; 
} 

function replace_string_callback($matches) 
{
  return randomString($matches[1]);
}
$input = "Dear {{Username}}, your entry code is :  {{random_string_5}}. 
And your OTP : {{random_number_6}}";
$pattern = '/\{\{random_number_(.*?)\}\}/i';
$result = preg_replace_callback($pattern, 'replace_string_callback', $input);
echo $result;
?>

That’s It.

If you are are developer and need help in coding or want to outsource your work. Please contact me on my Email ID : shishir.raven@gmail.com or my Skype ID : shishir.raven