str_shuffle

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

str_shuffleBir dizgenin karakterlerini devşirir

Açıklama

str_shuffle(string $dizge): string

str_shuffle() işlevi bir dizgeyi rasgele karar. Tüm olası devşirimleri oluşturulur (her çağrıda farklı bir sonuç döner).

Dikkat

Bu işlev kriptografik olarak güvenilir değerler üretmez ve kriptografik amaçlarla veya döndürülen değerlerin tahmin edilemez olmasını gerektiren amaçlarla kullanılmamalıdır.

Kriptografik olarak güvenilir rastgelelik gerekliyse Random\Randomizer sınıfı Random\Engine\Secure motoru ile kullanılabilir. Basit kullanım durumlarında random_int() ve random_bytes() işlevleri, işletim sisteminin CSPRNG’i tarafından desteklenen kullanışlı ve güvenli bir arayüz sağlar.

Bağımsız Değişkenler

dizge

Girdi dizgesi.

Dönen Değerler

Devşirilen dizge döner.

Sürüm Bilgisi

Sürüm: Açıklama
7.1.0 Libc rand işlevi yerine » Mersenne Twister Rastgele Sayı Üretecini kullanmak için dahili rastgelelik algoritması değiştirildi.

Örnekler

Örnek 1 - str_shuffle() örneği

<?php
$str
= 'abcdef';
$shuffled = str_shuffle($str);

// Çıktısı şöyle bir şey olur: baefcd
echo $shuffled;
?>

Ayrıca Bakınız

add a note add a note

User Contributed Notes 14 notes

up
115
jojersztajner at OXYGEN dot POLAND
17 years ago
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.

Hree's a cdoe taht slerbmcas txet in tihs way:
<?php
   
function scramble_word($word) {
        if (
strlen($word) < 2)
            return
$word;
        else
            return
$word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
    }

    echo
preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');
?>

It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
up
10
ronald
9 years ago
This page is missing a very important notice:

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
up
20
blamoo2 at hotmail dot com
9 years ago
This function is affected by srand():

<?php
srand
(12345);
echo
str_shuffle('Randomize me') . '<br/>'; // "demmiezr aon"
echo str_shuffle('Randomize me') . '<br/>'; // "izadmeo rmen"

srand(12345);
echo
str_shuffle('Randomize me') . '<br/>'; // "demmiezr aon" again
?>
up
25
qeremy [atta] gmail [dotta] com
12 years ago
A proper unicode string shuffle;

<?php
function str_shuffle_unicode($str) {
   
$tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
   
shuffle($tmp);
    return
join("", $tmp);
}
?>

$str = "Şeker yârim"; // My sweet love

echo str_shuffle($str); // i�eymrŢekr �

echo str_shuffle_unicode($str); // Şr mreyeikâ
up
2
ccb2357 at gmail dot com
1 year ago
<?php
   
function str_rand(int $length = 20) : string {
       
$ascii_codes = range(48, 57) + range(97, 122);
       
$codes_lenght = (count($ascii_codes)-1);
       
shuffle($ascii_codes);
       
$string = '';
        for(
$i = 1; $i <= $length; $i++){
           
$previous_char = $char ?? '';
           
$char = chr($ascii_codes[random_int(0, $codes_lenght)]);
            while(
$char == $previous_char){
               
$char = chr($ascii_codes[random_int(0, $codes_lenght)]);
            }
           
$string .= $char;
        }
        return
str_shuffle($string);
    }
?>
up
3
Anonymous
5 years ago
As noted in this documentation str_shuffle is NOT cryptographically secure, however I have seen many code examples online of people using nothing more than this to generate say random passwords.  So I though I'd share my function which while it makes use of str_shuffle also rely's on random_int() for added security. I use this function to generate salts to use when working with hashes but it can also be used to generate default passwords for new users for example.

It starts with a universe of possible characters, in this case all letters (upper and lower case), 0-9, and several special characters.

It then will run str_shuffle on the universe of characters a random number of times, using random_int() (currently set to 1-10)

Then once the universe of possible characters has been shuffled it using random_int() once more to select the character as a random position within the shuffled string, as does that once for each character you want in the output.

function secret_gen( $len=64 ) {
    $secret = "";
    $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=`~,<>.[]: |';
    for ( $x = 1l $x <= random_int( 1, 10 ), $x++ ){
        $charset = str_shuffle( $charset );
    }
    for ( $s = 1; $s <= $len; $s++ ) {
        $secret .= substr( $charset, random_int( 0, 86 ), 1 );
    }
    return $secret;
}
up
3
wmtrader at yandex dot ru
4 years ago
Unshuffle, using:
<?php
$string
= "Hello World!";

$seed = 1234567890;
mt_srand($seed);

echo
$sh = str_shuffle($string);  //print 'eloWHl rodl!'
echo str_unshuffle($sh, $seed); //print 'Hello World!'
?>

<?php
function str_unshuffle($str, $seed){
   
$unique = implode(array_map('chr',range(0,254)));
   
$none   = chr(255);
   
$slen   = strlen($str);
   
$c      = intval(ceil($slen/255));
   
$r      = '';
    for(
$i=0; $i<$c; $i++){
       
$aaa = str_repeat($none, $i*255);
       
$bbb = (($i+1)<$c) ? $unique : substr($unique, 0, $slen%255);
       
$ccc = (($i+1)<$c) ? str_repeat($none, strlen($str)-($i+1)*255) : "";
       
$tmp = $aaa.$bbb.$ccc;
       
mt_srand($seed);
       
$sh  = str_shuffle($tmp);
        for(
$j=0; $j<strlen($bbb); $j++){
           
$r .= $str{strpos($sh, $unique{$j})};
        }
    }
    return
$r;
}
up
6
CygnusX1
17 years ago
To cobine functionality and simplicity of the two functions below we can have:

<?php
function generatePasswd($numAlpha=6,$numNonAlpha=2)
{
  
$listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  
$listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';
   return
str_shuffle(
     
substr(str_shuffle($listAlpha),0,$numAlpha) .
     
substr(str_shuffle($listNonAlpha),0,$numNonAlpha)
    );
}
?>
up
4
Anonymous
10 years ago
str_shuffle isn't recommendable for passwords. Each character exists only one time).

A function like the following one is better for this.

<?php
   
function generatePassword($length = 8) {
       
$possibleChars = "abcdefghijklmnopqrstuvwxyz";
       
$password = '';

        for(
$i = 0; $i < $length; $i++) {
           
$rand = rand(0, strlen($possibleChars) - 1);
           
$password .= substr($possibleChars, $rand, 1);
        }

        return
$password;
    }
?>
up
0
Anonymous
14 years ago
Shuffle for all encoding formats

<?php

function unicode_shuffle($string, $chars, $format = 'UTF-8')
{
    for(
$i=0; $i<$chars; $i++)
       
$rands[$i] = rand(0, mb_strlen($string, $format));
           
       
$s = NULL;
           
    foreach(
$rands as $r)
       
$s.= mb_substr($string, $r, 1, $format);
           
    return
$s;
}

?>
up
-1
dzafel at op dot pl
17 years ago
Very, very simple random password generator, without using rand() function:

<?php
function random_password($chars = 8) {
  
$letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return
substr(str_shuffle($letters), 0, $chars);
}
?>
up
-2
krzysiekpiasecki at gmail dot com
9 years ago
/**
* Test shuffleString
*/
function testShuffleString() {
    $shuffled = shuffleString("ĄęźćÓ");
    if (\mb_strlen($shuffled) != 5) {
        throw new \UnexpectedValueException("Invalid count of characters");
    }
    if ($shuffled == "ĄęźćÓ") {
        throw new \UnexpectedValueException("The same string");
    }
    foreach (["Ą", "ę", "ź", "ć", "Ó"] as $char) {
        if (\mb_strpos($shuffled, $char) === false) {
            throw new \UnexpectedValueException("Character not found");
        }
    }
}

/**
* Shuffle string
*
* @param $stringValue String to shuffle
* @param string $startWith Shuffle $stringValue and append to $startWith
* @return string Shuffled string
* @author Krzysztof Piasecki<krzysiekpiasecki@gmail.com>
*/
function shuffleString($stringValue, $startWith = "") {
    $range = \range(0, \mb_strlen($stringValue));
    shuffle($range);
    foreach($range as $index) {
        $startWith .= \mb_substr($stringValue, $index, 1);
    }
    return $startWith;
};

testShuffleString();

echo shuffleString("Hello"); // > 'elHol' (something like this)
echo shuffleString("World!", "Hello "); // > 'Hello do!lrW' (something like this)
up
-1
kundanborakb at gmail dot com
4 years ago
<?php

//get random string with your desire length

   
function getRandom($length){
       
       
$str = 'abcdefghijklmnopqrstuvwzyz';
       
$str1= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
       
$str2= '0123456789';
       
$shuffled = str_shuffle($str);
       
$shuffled1 = str_shuffle($str1);
       
$shuffled2 = str_shuffle($str2);
       
$total = $shuffled.$shuffled1.$shuffled2;
       
$shuffled3 = str_shuffle($total);
       
$result= substr($shuffled3, 0, $length);

        return
$result;

    }

    echo
getRandom(8);

//output -->
//GATv3JPX
//g7AzhDtR
//DTboKtiL
//CuWZR4cs
//tmTXbzBC

?>
up
-11
Michiel van den boogaard
19 years ago
Shortend function for PHP < 4.3
<?php 
function RandomPass($numchar

   
$word = "a,b,c,d,e,f,g,h,i,j,k,l,m,1,2,3,4,5,6,7,8,9,0"
   
$array=explode(",",$word); 
   
shuffle($array); 
   
$newstring = implode($array,""); 
    return
substr($newstring, 0, $numchar); 

?>
To Top