PHP 7.1.0 Released

str_shuffle

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

str_shuffleMélange les caractères d'une chaîne de caractères

Description

string str_shuffle ( string $str )

str_shuffle() mélange les caractères d'une chaîne. Une permutation parmi toutes celles possibles est créée.

Attention

Cette fonction ne génère pas de valeurs sécurisées d'un point de vue cryptologie, et ne doit pas être utilisée dans un contexte de cryptologie. Si vous avez besoin d'un valeur sécurisée d'un point de vue cryptologique, utilisez plutôt random_int(), random_bytes(), ou openssl_random_pseudo_bytes().

Liste de paramètres

str

La chaîne d'entrée.

Valeurs de retour

Retourne la chaîne mélangée.

Exemples

Exemple #1 Exemple avec str_shuffle()

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

// Cela va afficher quelque chose comme : bfdaec
echo $shuffled;
?>

Voir aussi

  • shuffle() - Mélange les éléments d'un tableau
  • rand() - Génère une valeur aléatoire

add a note add a note

User Contributed Notes 10 notes

up
31
jojersztajner at OXYGEN dot POLAND
9 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
3
krzysiekpiasecki at gmail dot com
1 year 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
11
qeremy [atta] gmail [dotta] com
4 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
4
ronald
1 year 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
3
blamoo2 at hotmail dot com
1 year 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
4
Anonymous
6 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
2
Anonymous
2 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
3
dzafel at op dot pl
9 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
CygnusX1
9 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
-3
Michiel van den boogaard
11 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