如何在字符串的随机位置添加一个单一的随机字符(0-9或a-z或-或_)。
我可以按照以下步骤获取随机位置:
$random_position = rand(0,5);
现在我该如何获取一个随机数(0到9)或随机字符(a到z)或(-)或(_)?最后,我该如何在上述随机位置添加字符?
例如,以下是字符串:
$string = "abc123";
$random_position = 2;
$random_char = "_";
新的字符串应该是:
"a_bc123"
如何在字符串的随机位置添加一个单一的随机字符(0-9或a-z或-或_)。
我可以按照以下步骤获取随机位置:
$random_position = rand(0,5);
$string = "abc123";
$random_position = 2;
$random_char = "_";
"a_bc123"
$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;
substr_replace()
的使用 - 这是一个相当不错的替代方案,可以替换掉substr()
的使用。 - Phliplip<?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;
?>
rand()
应该像其他答案一样利用strlen()
。 - Phliplip$string = 'abc123';
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789-_';
$new_string = substr_replace(
$string,
$chars[rand(0, strlen($chars)-1)],
rand(0, strlen($string)-1),
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获取字符串长度:
$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;
这可能不是最好的方法,但我认为它应该可以解决问题...