Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Select 5 random characters in a string?

Tags:

php

How can I randomly select 5 characters from a given string? They can repeat.

Say my string is this:

static $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";

I just want 5 random characters out of that variable. Thanks to anyone who can help me out!

like image 535
Mrdoctor Kovacic Avatar asked Jan 17 '26 18:01

Mrdoctor Kovacic


2 Answers

function gen_code() {

    $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

    return substr(str_shuffle($charset), 0, 5);
}
like image 92
Wesley Brian Lachenal Avatar answered Jan 20 '26 07:01

Wesley Brian Lachenal


It's working Please Try it,

<?php
    $length = 5;
    $randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
    echo $randomString;
?>
like image 36
Ravi Avatar answered Jan 20 '26 07:01

Ravi