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条)

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services