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

8

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

我可以按照以下步骤获取随机位置:

$random_position = rand(0,5);

现在我该如何获取一个随机数(0到9)随机字符(a到z)(-)(_)?最后,我该如何在上述随机位置添加字符?
例如,以下是字符串:
$string = "abc123";
$random_position = 2;
$random_char = "_";

新的字符串应该是:
"a_bc123"

真的吗?那么位置0和1有什么区别? - Karoly Horvath
5个回答

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;

这个字符映射表包括大写字母,但是原帖似乎没有指明。 - Shef
1
好的,它可以,但是地图可以根据需求安全地进行编辑。 - khattam
@Shef,是的,我不想包含大写字母,但我已经将它们删除了。 - sunjie
2
请看@rrapuya对substr_replace()的使用 - 这是一个相当不错的替代方案,可以替换掉substr()的使用。 - Phliplip
@Phliplip,谢谢。我肯定做了。 - sunjie

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;
?>

我喜欢你的解决方案,你是唯一一个想到使用substr_replaces和零长度的人。从手册中可以看到; “当然,如果长度为零,则此函数将在给定的起始偏移处将替换插入字符串中。” 但是你在字符集中缺少数字、下划线和破折号,而且我认为sunjie不希望包括大写字母。另外,你的rand()应该像其他答案一样利用strlen() - Phliplip
我之前没有想过在rand()中利用strlen(),直到看到他们的答案才意识到。 - rrapuya

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

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

一个 $random_char_position 的值为2不就意味着 $random_char 变成了 '2' 吗?只是说一下 ;) - Phliplip

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;

这可能不是最好的方法,但我认为它应该可以解决问题...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接