首页 > 解决方案 > 在PHP中将字符串的随机字母大写

问题描述

我想将字符串中的随机字母大写并将完整的句子从hello69.world回显到HeLlO69.WoRlD。每次函数运行时,它应该将随机字母大写并排除特殊字符和数字。到目前为止我已经尝试过了,但它每次只选择字符串中的前 5 个字符,并且只输出大写字母。如何解决这个问题?

<?php
 $string = "hellohg.09ui8vkosjbdh";

    $selchr = substr($string,0, 5);
    $caps = strtoupper($selchr);
    echo substr_replace($string, $caps,0);
?>

标签: phpstringrandomreplace

解决方案


假设您要随机大写 5 个字母:

$string = "hellohg.09ui8vkosjbdh";
$characters = str_split($string);
$i = 0;
do{
    $random_index = rand(0, count($characters) - 1);
    $unique_indices[] = ""; //UNIQUE INDICES
    while (in_array($random_index, $unique_indices)) {
        $random_index = rand(0, count($characters) - 1);
    }
    $unique_indices[] = $random_index;

    $random_letter = $characters[$random_index];
    if(ctype_alpha($random_letter)){//only letters 
        $characters[$random_index] = strtoupper($random_letter);
        $i++;
    }
}while($i<5);echo implode('', $characters);

感谢@El_Vanja 的注意UNIQUE INDICES


推荐阅读