2015-04-30 32 views
2
用下划线(_)替换字符串多个随机字符

我使用像“gjhyYhK”,“HJjhkeuJ”等代码,但希望用户展示这些代码,如:如何在PHP

gj_y__K

HJj__e_J

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

+0

多大比例的字符你想要更换? –

+0

priyanka显示你试过什么?把你的代码以及 –

+0

嗨帕拉!我想删除40%的字符。 –

回答

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值。这将保证你得到你想要的,只要多少突显,只要你想比字符串的长度较少

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

让我的功能知道是否有其他需要帮助

+0

你正在改变字符串的长度 - 所有的字符仍然存在,以相同的顺序。只是与他们之间的下划线 –

+0

@pala_答案更新,请删除downvote .. –

-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; 
+0

AD_FJ,ADF_J,A_D_FJ这就是我正在得到 –

+0

运行它一些。你会明白我的意思。更何况你实际上并没有取代任何字符,只是将字符串拉伸出来 –

+0

你现在可以试试。编辑答案 –

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