Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I randomize an entire string of 62 characters?

Tags:

php

I have 62 base64 characters that I want to randomize. How can I do this using PHP? The string would be all letters, upper and lower case as well as numbers from 0-9.

The thing that is most important to me is that the entire string be evaluated before a return value is given. In other words, if I request a string of 8 characters in length and my string starts out like:

1234567890ABCDE..... I don't want to get the first 8 numbers randomized. It should randomize the entire string first, then return 8 characters from that.

like image 681
Jim Avatar asked Feb 22 '10 10:02

Jim


People also ask

How do you random a string?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer.

How do I randomize a string in SQL?

If you need a string of random digits up to 32 characters for test data or just need some junk text to fill a field, SQL Server's NEWID() function makes this simple. NEWID() is used to create a new GUID (globally unique identifier), and we can use that as a base to get a string of random characters.

How do you create a random string length?

Method 1: Using Math. random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.


2 Answers

Try this:

$string = '1234567890ABCDE...';

$string = substr(str_shuffle($string), 0, 8);

str_shuffle randomizes the string, then substr takes the first 8 characters from it.

like image 66
Tatu Ulmanen Avatar answered Oct 12 '22 23:10

Tatu Ulmanen


Take a look at str_shuffle.

like image 27
Yacoby Avatar answered Oct 12 '22 23:10

Yacoby