php - 在PHP中将字符串的随机字母大写
问题描述
我想将字符串中的随机字母大写并将完整的句子从hello69.world回显到HeLlO69.WoRlD。每次函数运行时,它应该将随机字母大写并排除特殊字符和数字。到目前为止我已经尝试过了,但它每次只选择字符串中的前 5 个字符,并且只输出大写字母。如何解决这个问题?
<?php
$string = "hellohg.09ui8vkosjbdh";
$selchr = substr($string,0, 5);
$caps = strtoupper($selchr);
echo substr_replace($string, $caps,0);
?>
解决方案
假设您要随机大写 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
推荐阅读
- python - 如何将删除请求重定向到 django rest 框架中的特定 url?
- spring-boot - ibm mq 消费者的连续连接重试尝试导致一段时间后内存泄漏导致 jvm 崩溃。如何解决这个问题?
- ios - Unable to simultaneously satisfy constraints. Probably at least one of the constraints
- android - 如何避免 listview android 应用程序崩溃
- python - Numba,Numpy:在并行 @jit 函数中调用 @guvectorized 函数
- node.js - 在 systemctl 服务文件中从 ExecStart 运行 npm start
- c# - 如何在 Rx.Net 中实现排气映射处理程序?
- entity-relationship - 有什么方法可以自动将 EER - 模型转换为维度模型?
- reactjs - react如何改变react数组中对象的值
- for-loop - 三个嵌套循环的时间复杂度?