略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: str_shuffle

2024-04-20

str_shuffle

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

str_shuffle随机打乱一个字符串

说明

str_shuffle(string $str): string

str_shuffle() 函数打乱一个字符串,使用任何一种可能的排序方案。

警告

本函数并不会生成安全加密的值,不应用于加密用途。若需要安全加密的值,考虑使用 random_int()random_bytes()openssl_random_pseudo_bytes() 替代。

参数

str

输入字符串。

返回值

返回打乱后的字符串。

更新日志

版本 说明
7.1.0 内置的随机算法从 libc rand 函数改成了» 梅森旋转演伪随机数发生算法。

范例

示例 #1 str_shuffle() 范例

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

// 输出类似于: bfdaec
echo $shuffled;
?>

参见

add a noteadd a note

User Contributed Notes 13 notes

up
108
jojersztajner at OXYGEN dot POLAND
15 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
17
blamoo2 at hotmail dot com
6 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
9
ronald
6 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
24
qeremy [atta] gmail [dotta] com
10 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
3
Anonymous
2 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
5
CygnusX1
15 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
1
wmtrader at yandex dot ru
2 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
1
Anonymous
7 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
-1
kundanborakb at gmail dot com
2 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
0
Anonymous
12 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.=

官方地址:https://www.php.net/manual/en/function.str-shuffle.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3