如何用PHP中的下划线(_)替换字符串中的多个随机字符

时间:2015-04-30 05:35:59

标签: php replace

我使用的代码如" gjhyYhK"," HJjhkeuJ"等但是希望用户显示以下代码:

gj_y__K

HJj__e_J

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

4 个答案:

答案 0 :(得分:0)

这将做你想要的:

  $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的值。这将保证您获得所需的下划线数,只要您想要少于字符串的长度

答案 1 :(得分:0)

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

<?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;
?>

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

答案 2 :(得分:0)

试试这个:

$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);

答案 3 :(得分:-1)

$str = "ADFJ";
$strlen = strlen($str);
$newStr = '';
for ($i = 0; $i < $strlen; $i++) {
    if ($i == rand(0, $strlen)) {
        $newStr .= '_';
    } else {
        $newStr .= $str[$i];
    }
}
echo $newStr;