Random string rules - php

I have a function that generates a random 3-character alpha-numeric string. I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random.
function generate_random($length = 3) {
$characters = '123456789ABCDEFGHJKLMNPRSTUVWXYZ';
$rand_str = '';
for ($p = 0; $p < $length; $p++) {
$rand_str .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $rand_str;
}
I need to modify it in such a way that the new string consisted of 2 alpha and 2 numeric characters. The combination of numbers and letters can be random. How do I do that?

I would personally do it this way:
function generate_random($countAlpha = 2, $countNumeric = 2, $randomize = true) {
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$numeric = '123456789';
$rand_str = '';
for ($p = 0; $p < $countAlpha; $p++) {
$rand_str .= $alpha[mt_rand(0, strlen($alpha)-1)];
}
for ($p = 0; $p < $countNumeric; $p++) {
$rand_str .= $numeric[mt_rand(0, strlen($numeric)-1)];
}
if($randomize) {
$rand_str = str_split($rand_str);
shuffle($rand_str);
return implode($rand_str);
}
return $rand_str;
}
Inside I have 2 for loops, each one based on parameters $countAlpha and $countNumeric. I also have a 3rd parameter, $randomize that will allow you to randomize the output if you wish.

You could separe numbers and letter. Then, append N values of each into an array, shuffle it, and the implode to get your string:
function generate_random($nNumbers = 2, $nAlpha = 2) {
// prepare data to use
$num = '123456789';
$numlen = strlen($num) - 1;
$alpha = 'ABCDEFGHJKLMNPRSTUVWXYZ';
$alphalen = strlen($alpha) - 1;
$out = []; // New array
// generate N numbers
for ($i = 0; $i < $nNumbers ; $i++) {
$out[] = $num[mt_rand(0, $numlen)];
}
// generate N letters
for ($i = 0; $i < $nAlpha ; $i++) {
$out[] = $alpha[mt_rand(0, $alphalen)];
}
shuffle($out); // Shuffle the array
return implode($out); // Convert to string
}
echo generate_random() ;
// echo generate_random(2, 4) ; // example

Related

How to generate a random pattern of *&# in PHP

Hello there i am making a program which will let me help generate a random string with a specified limit and random strings of *&# but then the combination of *&# should not repeat.
Ex: if I input 3 then the O/P should be
#**
**#
**#
It should generate a random string of length 3 up to 3 rows with different patterns also the pattern should not repeat. I am using the below code but not able to attain it.
$n = 3;
for($i = 0; $i < n; $i++)
{
for($j=0;$j<=$n;j++)
{
echo "*#";
}
echo "<br />";
}
But I am not able to generate the output, where is my logic failing?
If you want to make sure the same pattern doesn't show up more than once you'll have to keep a record of the generated strings. In the most basic form it could look like this:
public function generate() {
$amount = 3; // The amount of strings you want.
$generated_strings = []; // Keep a record of the generated strings.
do {
$random = $this->generateRandomString(); // Generate a random string
if(!in_array($random, $generated_strings)) { // Keep the record if its not already present.
$generated_strings[] = $random;
}
} while(sizeof($generated_strings) !== $amount); // Repeat this process until you have three strings.
print_r($generated_strings);
}
public function generateRandomString($length = 3) {
$characters = '*&#';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Not necessarily the most optimized algorithm but it should work.
I am using a string generator, somewhat random, combining the chars you have provided. The second part is filling the output array with generated strings that are not already present.
<?php
function randomize($n) {
$s = '';
for ($i = 0; $i < $n; $i++) {
$s. = (rand(0, 10) < 5 ? '*' : '#');
}
return $s;
}
$n = 3;
$output = array();
for ($i = 0; $i < $n; $i++) {
$tmp = randomize($n);
while (in_array($tmp, $output)) {
$tmp = randomize($n);
}
$output[] = $tmp;
}
print_r($output);
Visible here
You can use a while loop and array unique to do this.
I first have an array with possible chars.
Then I loop until result array is desired lenght.
I use array unique to remove any duplicates inside the loop.
I use rand(0,2) to "select" a random character from possible characters array.
$arr = ["*", "&", "#"];
$res = array();
$n =7;
While(count($res) != $n){
$temp="";
For($i=0;$i<$n;$i++){
$temp .= $arr[Rand(0,count($arr)-1)];
}
$res[] = $temp;
$res = array_unique($res);
}
Var_dump($res);
https://3v4l.org/Ko4Wd
Updated with out of scope details not clearly specified by OP.

How to generate a random 6-character string with alternating letters and numbers?

I have a code in PHP that is able to generate a 6-character alpha-numeric string but it does not ensure that there are 3 letters and 3 numbers generated.
It generates a string such as "ps7ycn"
It does not have 3 numbers in between the alphabet.
The numbers should be in between the letters.
example : a3g5h9
This will ensure you only get alternating letters and numbers:
Code: (Demo)
$letters='abcdefghijklmnopqrstuvwxyz'; // selection of a-z
$string=''; // declare empty string
for($x=0; $x<3; ++$x){ // loop three times
$string.=$letters[rand(0,25)].rand(0,9); // concatenate one letter then one number
}
echo $string;
Potential Outputs:
i9f6q0
j4u5p4
j6l6n9
p.s. If you want to randomize whether the first character is a letter or number, use this line of code after the for loop.
if(rand(0,1)){$string=strrev($string);}
rand() will generate a 0 or a 1, the conditional will treat 0 as false and 1 as true. This offers a "coin flip" scenario regarding whether to reverse the string or not.
If you want to guarantee unique letters and numbers in the output...
$letters=range('a','z'); // ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
shuffle($letters);
$numbers=range(0,9); // [0,1,2,3,4,5,6,7,8,9]
shuffle($numbers);
$string='';
for($x=0; $x<3; ++$x){
$string.=$letters[$x].$numbers[$x];
}
echo $string;
Try this code:
$str = '';
for ( $i = 1; $i <= 6; ++$i ) {
if ( $i % 2 ) {
$str .= chr(rand(97,122));
}else{
$str .= rand(0,9);
}
}
This one is shorter but you can not use it to have odd length like a1g7y5k :
$str = '';
for ( $i = 1; $i <= 3; ++$i ) {
$str .= chr(rand(97,122)) . rand(0,9);
}
-Alternatively use this method that can be improved ( refer to mickmackusa's comments):
$alphas = 'abcdefghijklmnopqrstuvwxyz';
$numbers = '0123456789';
$arr1 = str_split($alphas);
$arr2 = str_split($numbers);
$arr3 = array_rand($arr1,3);
$arr4 = array_rand($arr2,3);
$arr5 = array();
for ($i=0; $i<count($arr3); $i++) {
$arr5[] = $arr3[$i];
$arr5[] = $arr4[$i];
}
$result = implode('',$arr5);
Check this thread.It has some good ideas and functions.
Here's one way you could address this:
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$number = '0123456789';
$random = '';
for ( $i = 0; $i < 6; ++$i ) {
if ( $i % 2 ) {
$random .= substr( $number, rand( 0, strlen( $number ) - 1 ), 1 );
} else {
$random .= substr( $alpha, rand( 0, strlen( $alpha ) - 1 ), 1 );
}
}
$random will now contain a six-character random value with the first, third, and fifth characters coming from $alpha and second, fourth, and sixth characters coming from $number.
You can use this function
<?php
public static function random_string($charsNo = 3, $NumbersNo = 3)
{
$character_set_array = array();
$character_set_array[] = array('count' => $charsNo, 'characters' => 'abcdefghijklmnopqrstuvwxyzasdsawwfdgrzvyuyiuhjhjoppoi');
$character_set_array[] = array('count' => $NumbersNo, 'characters' => '0123456789');
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set['count']; $i++) {
$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
}
}
shuffle($temp_array);
return implode('', $temp_array);
}
?>

PHP - How to create all possibility from a string

Here, there is a example string "XjYAKpR" .. how to create all new string possibility with that string ??
I've tried before
function containAllRots($s, $arr) {
$n = strlen($s);
$a = array();
for ($i = 0; $i < $n ; $i++) {
$rotated = rotate(str_split($s), $i);
$a[] = $rotated;
}
print_r($a);die();
if (array_diff($arr, $a)) {
return True;
}
else
{
return False;
}
}
I make 2 function rotate and generate
function rotate($l, $n) {
$b = $l[$n];
$sisa = array_values(array_diff($l, array($b)));
for ($i = 0; $i < count($sisa) ; $i++) {
$random[] = generate($sisa, $b);
}
print_r($random);die();
$hasil = $l[$n] . implode("",$random);
return $hasil;
}
function generate($sisa, $b) {
$string = implode("",$sisa);
$length = count($sisa);
$size = strlen($string);
$str = '';
for( $i = 0; $i < $length; $i++ ) {
$str .= $string[ rand( 0, $size - 1 ) ];
}
Here there is a pair of functions that lets you calculate a permutation set
(no repetitions are taken in account)
function extends_permutation($char, $perm) {
$result = [];
$times = count($perm);
for ($i=0; $i<$times; $i++) {
$temp = $perm;
array_splice($temp, $i, 0, $char);
array_push($result, $temp);
}
array_push($result, array_merge($perm, [$char]));
return $result;
}
function extends_set_of_permutations($char, $set) {
$step = [];
foreach ($set as $perm) {
$step = array_merge($step, extends_permutation($char, $perm));
}
return $step;
}
you can use them to generate the required set of permutations. Something like this:
$seed = "XjYAKpR";
// the first set of permutations contains only the
// possible permutation of a one char string (1)
$result_set = [[$seed[0]]];
$rest = str_split(substr($seed,1));
foreach($rest as $char) {
$result_set = extends_set_of_permutations($char, $result_set);
}
$result_set = array_map('implode', $result_set);
sort($result_set);
At the end of the execution you will have the 5040 permutations generated by your string in the result_set array (sorted in alphabetical order).
Add a char and you will have more than 40000 results.
The functions are quite naive in implementation and naming, both aspects can be improved.

Auto incrementing unique url

I am looking to create an auto incrementing unique string using PHP, containing [a-Z 0-9] starting at 2 chars long and growing when needed.
This is for a url shrinker so each string (or alias) will be saved in the database attached to a url.
Any insight would be greatly appreciated!
Note this solution won't produce uppercase letters.
Use base_convert() to convert to base 36, which will use [a-z0-9].
<?php
// outputs a, b, c, ..., 2o, 2p, 2q
for ($i = 10; $i < 99; ++$i)
echo base_convert($i, 10, 36), "\n";
Given the last used number, you can convert it back to an integer with intval() increment it and convert the result back to base 36 with base_convert().
<?php
$value = 'bc9z';
$value = intval($value, 36);
++$value;
$value = base_convert($value, 10, 36);
echo $value; // bca0
// or
echo $value = base_convert(intval($value, 36) + 1, 10, 36);
Here's an implementation of an incr function which takes a string containing characters [0-9a-zA-Z] and increments it, pushing a 0 onto the front if required using the 'carry-the-one' method.
<?php
function incr($num) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$parts = str_split((string)$num);
$carry = 1;
for ($i = count($parts) - 1; $i >= 0 && $carry; --$i) {
$value = strpos($chars, $parts[$i]) + 1;
if ($value >= strlen($chars)) {
$value = 0;
$carry = 1;
} else {
$carry = 0;
}
$parts[$i] = $chars[$value];
}
if ($carry)
array_unshift($parts, $chars[0]);
return implode($parts);
}
$num = '0';
for ($i = 0; $i < 1000; ++$i) {
echo $num = incr($num), "\n";
}
If your string was single case rather than mixed, and didn't contain numerics, then you could literally just increment it:
$testString="AA";
for($x = 0; $x < 65536; $x++) {
echo $testString++.'<br />';
}
$testString="aa";
for($x = 0; $x < 65536; $x++) {
echo $testString++.'<br />';
}
But you could possibly make some use of this feature even with a mixed alphanumeric string
To expand on meagar's answer, here is how you can do it with uppercase letters as well and for number arbitrarily big (requires the bcmath extension, but you could as well use gmp or the bigintegers pear package):
function base10ToBase62($number) {
static $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$result = "";
$n = $number;
do {
$remainder = bcmod($n, 62);
$n = bcdiv($n, 62);
$result = $chars[$remainder] . $result;
} while ($n > 0);
return $result;
}
for ($i = 10; $i < 99; ++$i) {
echo base10ToBase62((string) $i), "\n";
}

PHP Random Number

I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.

Categories