【问题标题】:Add a random character to a string after every character [closed]在每两个字符之间的字符串中添加一个随机字符[关闭]
【发布时间】:2022-11-12 18:54:07
【问题描述】:

如何每隔一个字符将[A-Za-z0-9]/-中的随机字符添加到字符串中? 例如 输入:

Hello_world!

输出:

H3e7l2l-o2_aWmocr9l/db!s

编辑: 这是我尝试过的方法,但会引发错误,而且我不知道其他方法:

<?php
$string = "Hello_World!";
$length = strlen($string);
$string = str_split($string, 2);
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-";

for($i = 0; $i < ($length / 2); $i++){
  $char = substr(str_shuffle(str_repeat($chars, 1)), 0, 1);
  $added = implode($string[$i], $char); //this throws an error "Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array"
}

echo $string;

?>

【问题讨论】:

  • 遍历字符串中的字符。将字符后跟一个随机字符附加到结果字符串。你在这方面有什么问题?
  • 你自己尝试过什么吗?
  • @mikerojas 是的。我知道如何生成随机字符,我使用 split 和 implode 添加字符。然而,它是同一个字符。我不知道如何让它每次都随机。抱歉,我没有发布,但我目前无法访问那台计算机,我现在需要答案。
  • @Barmar 我使用 split 和 implode 每秒添加一个随机字符,但是循环它是一种有效的方法吗?
  • 担心效果第一的一旦你有了一个可行的解决方案,就会提高效率。

标签: php


【解决方案1】:
$str = 'Hello_world!';
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-';
$result = array_reduce(str_split($str),
  fn($carry, $item)=>$carry.=$item.$chars[rand(0,strlen($chars)-1)], '');
print_r($result);

str_split 将您的输入字符串拆分为字符,然后array_reduce 将它们与添加的随机字符重新组合。

【讨论】:

    【解决方案2】:
    <?PHP
      $str =  "Hello World!";
      
      $new_string = '';
      for($i =0; $i < strlen($str); $i++){ // loop through the string
         $new_string .= $str[$i]; // add character to new string
         $new_string .= getRandomCharacter(); // add the random character to new string
      }
      echo $new_string;
      
      function getRandomCharacter(){
         $random_characters = 'abcdefghijklmnopqrstuvwxyz'
                     .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                     .'0123456789!@#$%^&*()';
        $index= rand(0, (strlen($random_characters)- 1) ); // generates random character index from the given set.
        return $random_characters[$index];
      }
      
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-04
      • 2014-02-26
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多