str_shuffle

(PHP 4 >= 4.3.0, PHP 5)

str_shuffleПереставляет символы в строке случайным образом

Описание

string str_shuffle ( string $str )

str_shuffle() перемешивает символы в строке. Выбирается одна возможная перестановка из всех возможных.

Список параметров

str

Входная строка.

Возвращаемые значения

Возвращает перемешанную строку.

Примеры

Пример #1 Пример использования str_shuffle()

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

// выведет что-то вроде этого: bfdaec
echo $shuffled;
?>

Смотрите также

  • shuffle() - Перемешивает массив
  • rand() - Генерирует случайное число

Коментарии

You can use str_shuffle to make simple and nice random passwords:

function random_passwd($numchar) {
      $string =str_shuffle("abcefghijklmnopqrstuvwxyz1234567890");
      $password = substr($string,1,$numchar);

      return($password);
}

echo random_passwd('8') // Will return something like "xa3dh214" =)
2004-08-26 11:28:17
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
2004-08-26 18:31:47
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
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($newstring0$numchar); 

?>
2005-01-17 04:03:38
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Here are 2 functions, one inverts the case of a string and the other one randomizes the captilization in a string, kinda 
useful string operations.

<?

//Inverts the case of a string
function invert_case($str)
{
   
$nstr '';
    for(
$i=0;$i<strlen($str);$i++)
    {
       
$char substr($str,$i,1);
       
//If it's lower case make it upper case
       
if($char == strtolower($char))
        {
           
$char strtoupper($char);
        }
        else 
//if it's upper than make it lower
       
{
           
$char strtolower($char);
        }
       
$nstr .= $char;
    }
    return 
$nstr;
}

//Randomly capilizes/uncaptilizes chars in a string
function rand_case($str)
{
   
$nstr '';
    for(
$i=0;$i<strlen($str);$i++)
    {
       
$char substr($str,$i,1);
       
$char invert_case($char);
       
//2 options, to change or not to change
       
rand(0,1) == $char invert_case($char) : null;
       
$nstr .= $char;
    }
    return 
$nstr;
}

//Example:
echo rand_case("pHp rooLz! gUyZ"); //produces something random
echo invert_case("pHP STRiNG sEx");//produces Php strIng SeX
?>
2005-07-01 22:20:00
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Автор:
(correction)
I balked at the loop method used below in inverting and randomising capitalisation and released that we just need to flip the bit (3rd bit or 6th depending on what way you look at it) and it would cause the case change in a character.

Full code and example:
http://www.pgregg.com/projects/php/code/str_case.php
(append an s to the url to get the .phps source)

I came up with a method and thanks to arpad (optimising as ever! :) we now have:

Invert case:
preg_replace('/[a-z]/ie', '\'$0\' ^ str_pad(\'\', strlen(\'$0\'), \' \')', $input);

Randomise case:
preg_replace('/[a-z]/ie', '(rand(0,1) ? \'$0\' ^ str_pad(\'\', strlen(\'$0\'), \' \') : \'$0\')', $input);

and for good measure:
Upper case:
preg_replace('/[a-z]/e', '\'$0\' & str_pad(\'\', strlen(\'$0\'), chr(223))', $input);

Lower case:
preg_replace('/[A-Z]/e', '\'$0\' | str_pad(\'\', strlen(\'$0\'), \' \')', $input);
2005-08-05 07:20:07
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Just an update to sfalcon's function.  Chooses a random number within the length and then selects a random segment not the current segment of 1 to $numchar. Also added upper-case chars.

function random_passwd($numchar=8) {
    $str = "abcefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $start = mt_rand(1, (strlen($str)-$numchar));
    $string = str_shuffle($str);
    $password = substr($string,$start,$numchar);
    return($password);
}
2005-08-15 17:03:08
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Just another update to password builder function. With this version, you can choose the number of alphanumeric characters to add and the number of non-alphanumeric characters. You obtain a more secure password. You can add another characters to the non-alphanumeric list if you need.
If you want a password with 8 alphanumeric and 3 non-alphanumeric characters in a random order, just call :
random_passwd(8,3);

function generatePasswd($numAlpha=6,$numNonAlpha=2) {
    $pwd = '';
    $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';

    $start = mt_rand(1, (strlen($listAlpha)-$numAlpha));
    $string = str_shuffle($listAlpha);
    $pwd .= substr($string,$start,$numAlpha);

    $start = mt_rand(1, (strlen($listNonAlpha)-$numNonAlpha));
    $string = str_shuffle($listNonAlpha);
    $pwd .= substr($string,$start,$numNonAlpha);

    return str_shuffle($pwd);
}
2005-11-03 06:38:28
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
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);
}
?>
2006-12-29 15:16:01
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Автор:
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)
    );
}
?>
2007-02-14 15:17:26
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
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($word1, -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.
2007-06-16 06:27:30
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Re: jojersztajner at OXYGEN dot POLAND

"It may be useful if you want to create an accessible CAPTCHA."

This is a flawed concept, since:

1) It's not really accessible -- your scrambled text would produce incomprehensible output if passed through a screen reader (just imagine what a computer saying "uinervtisy" would sound like)

2) It's in no way secure.  A simple script with access to a copy of /usr/dict/words can reduce the space of possible solutions to no more than a handful.

i.e., it's trivial for a script to generate a command like the following, which solves the "uinervtisy" example 100% of the time:

php@server:~$ egrep -i '^u[inervts]{8}y$' /usr/share/dict/words
university
php@server:~$

Novel idea, but it would take a clever spammer all of 5 minutes to defeat it completely.
2008-01-24 13:46:16
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
<?php
$a 
str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890');
echo 
substr($a,0,6);
?>
Creates a nice 6 digit unique ID similar to that of tinyurl.
2009-04-09 16:51:59
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Here are nice functions for invert/randomize/alter the capitalization of a string.

<?php
function invert_case$str ) {
    for( 
$i 0$i strlen$str ); ++$i ) {
       
$ret .= ( $str$i ] == strtolower$str$i ] ) ) ? strtoupper$str$i ] ) : strtolower$str$i ] );
    }
   
    return 
$ret;
}

function 
rand_case$str ) {   
    for( 
$i 0$i strlen$str ); ++$i ) {
       
$ret .= ( rand0) == ) ? strtolower$str$i ] ) : strtoupper$str$i ] );
    }
   
    return 
$ret;
}

function 
alter_case$str ) {
    for( 
$i 0$i strlen$str ); ++$i ) {
       
$ret .= ( $i == ) ? strtoupper$str$i ] ) : strtolower$str$i ] );
    }
   
    return 
$ret;
}
?>

Examples:

<?php
# o RATO ROEU A ROUPA DO REI DE ROMA.
echo invert_case'O rato roeu a roupa do rei de roma.' );

# o RATo RoEU A ROUpA Do reI De rOma.
echo rand_case'O rato roeu a roupa do rei de roma.' );

# O RaTo rOeU A RoUpA Do rEi dE RoMa.
echo alter_case'O rato roeu a roupa do rei de roma.' );
?>
2010-04-01 14:11:02
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
Автор:
Shuffle for all encoding formats

<?php

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

?>
2010-06-21 13:32:26
http://php5.kiev.ua/manual/ru/function.str-shuffle.html
A proper unicode string shuffle;

<?php
function str_shuffle_unicode($str) {
   
$tmp preg_split("//u"$str, -1PREG_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â
2012-02-24 13:58:50
http://php5.kiev.ua/manual/ru/function.str-shuffle.html

    Поддержать сайт на родительском проекте КГБ