PHP:如何在随机位置的字符串中添加随机字符

时间:2011-06-28 07:41:01

标签: php string

如何在字符串中的随机位置添加单个随机字符(0-9或a-z或 - 或_)。

我可以通过以下方式获得随机位置:

$random_position = rand(0,5);

现在如何获得随机数(0到9) OR 随机字符(a到z) OR ( - ) OR (_)

最后我如何在上面的随机位置添加字符到上面的字符串。

例如以下是字符串:

$string = "abc123";
$random_position = 2;
$random_char = "_";

新字符串应为:

"a_bc123"

5 个答案:

答案 0 :(得分:5)

$string = "abc123";
$random_position = rand(0,strlen($string)-1);
$chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789-_";
$random_char = $chars[rand(0,strlen($chars)-1)];
$newString = substr($string,0,$random_position).$random_char.substr($string,$random_position);
echo $newString;

答案 1 :(得分:2)

尝试这样的事情

<?php 

   $orig_string = "abc123";
   $upper =strlen($orig_string);
   $random_position = rand(0,$upper);
   $int = rand(0,51);
   $a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
   $rand_char = $a_z[$int];


   $newstring=substr_replace($orig_string, $rand_char, $random_position, 0);

   echo 'original-> ' .$orig_string.'<br>';
   echo 'random-> ' .$newstring;
?>

答案 2 :(得分:1)

$string = 'abc123';
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_';
$new_string = substr_replace(
    $string,
    $chars[rand(0, strlen($chars)-1)],
    rand(0, strlen($string)-1),
    0
);

答案 3 :(得分:0)

// map of characters
$map = '0123456789abcdefghijklmnopqrstuvwxyz-_';
// draw a random character from the map
$random_char_posotion = rand(0, strlen($map)-1); // say 2?
$random_char = $map[$random_char_posotion]; // 2

$str = 'abc123';

// draw a random position
$random_position = rand(0, strlen($str)-1); // say 3?

// inject the randomly drawn character
$str = substr($str, 0, $random_position).$random_char.substr($str,$random_position);

// output the result
echo $str; // output abc2123

答案 4 :(得分:0)

获取字符串长度:

$string_length = strlen($string);//getting the length of the string your working with
$random_position = 2;//generate random position

生成“随机”字符:

$characters = "abcd..xyz012...89-_";//obviously instead of the ... fill in all the characters - i was just lazy.

从字符串中获取随机字符:

$random_char = substr($characters, rand(0,strlen($characters)), 1);//if you know the length of $characters you can replace the strlen with the actual length

将字符串分为两部分:

$first_part = substr($string, 0, $random_position);
$second_part = substr($string, $random_position, $string_length);

添加随机字符:

$first_part .=  $random_char;

将两者组合在一起:

$new_string = $first_part.$second_part;

这可能不是最好的方法,但我认为应该这样做......