【问题标题】:How to replace multiple random characters in string with underscore(_) in PHP如何在PHP中用下划线(_)替换字符串中的多个随机字符
【发布时间】:2015-07-09 16:25:58
【问题描述】:

我正在使用“gjhyYhK”、“HJjhkeuJ”等代码。但希望用户显示这些代码:

gj_y__K

HJj__e_J

表示将在代码中的随机位置用“_”编辑代码。

【问题讨论】:

  • 你想替换百分之几的字符?
  • priyanka 显示您尝试过的内容??把你的代码也放进去
  • 嗨,伙计!我想删除 40% 的字符。
  • 感谢您提供的答案

标签: php replace


【解决方案1】:

这会做你想做的事:

  $str = "gjhyYhK";

  $len = strlen($str);
  $num_to_remove = ceil($len * .4); // 40% removal
  for($i = 0; $i < $num_to_remove; $i++)
  {
    $k = 0;
    do
    {
      $k = rand(1, $len);
    } while($str[$k-1] == "_");
    $str[$k-1] = "_";
  }
  print $str . "\n";

如果您需要更多下划线,请更改 $underscores 的值。这将保证你得到你想要的下划线数量,只要你想要少于字符串的长度

【讨论】:

    【解决方案2】:

    您可以尝试下面的代码来获得您正在寻找的功能

    <?php
    $string = "gjhyYhK";
    $percentage = 40;
    $total_length = strlen($string);
    $number_of_underscore = floor(($percentage / 100) * $total_length); // I have use floor value, you can use ceil() as well
    for ($i = 1; $i <= $number_of_underscore; $i++)
    {
        $random_position = rand(0, strlen($string) - 1); // get the random position of character to be replaced
        if (substr($string, $random_position, 1) !== '_') // check if its already replaced underscore (_)
        {
            $string = preg_replace("/" . (substr($string, $random_position, 1)) . "/", '_', $string, 1); // here preg_replaced use to replace the character only once,  (i.e str_replace() will replace all matching characters)
        }
        else
        {
            $i--; // else decrement $i for the loop to run one more time
        }
    }
    echo $string;
    ?>
    

    如果需要任何其他帮助,请告诉我

    【讨论】:

    • 您正在更改字符串的长度 - 所有字符仍然存在,并且顺序相同。只是它们之间的下划线
    【解决方案3】:
    $str = "ADFJ";
    $strlen = strlen($str);
    $newStr = '';
    for ($i = 0; $i < $strlen; $i++) {
        if ($i == rand(0, $strlen)) {
            $newStr .= '_';
        } else {
            $newStr .= $str[$i];
        }
    }
    echo $newStr;
    

    【讨论】:

    • AD_FJ,ADF_J,A_D_FJ 这就是我得到的
    • 再运行一些。你会明白我的意思。更不用说您实际上并没有替换任何字符,只是将字符串拉长
    • 你现在可以试试。,编辑答案
    • a) 我没有投票。 b) 其他答案是错误的。他们仍然是。
    【解决方案4】:

    试试这个:

    $string=array(
        'gjhyYhK',
        'HJjhkeuJ'
    );
    $arr=array();
    foreach ($string as $key=>$value) {
        $arr[$key]='';
        for ($i=1; $i <=strlen($value); $i++) {
            if(rand(0,1)){
                $arr[$key].=substr($string[$key],$i,1);
            }else{
                $arr[$key].='_';
            }
        }
    }
    var_dump($arr);
    

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 2012-03-31
      • 2017-04-01
      • 1970-01-01
      • 2017-05-20
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      相关资源
      最近更新 更多