dongzhui2636 2011-06-28 07:41
浏览 348
已采纳

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

How can i add a single random character (0-9 or a-z or - or _) at a random place in a string.

I can get the random position by following:

$random_position = rand(0,5);

Now How can i get a random number ( 0 to 9 ) OR random character (a to z) OR (-) OR (_)

and finally how i can add character to the above string in the above random position.

For example following is string:

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

the new string should be:

"a_bc123"
  • 写回答

5条回答 默认 最新

  • dongquming3255 2011-06-28 07:48
    关注
    $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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致