dtx63505 2015-04-28 22:22
浏览 56
已采纳

我希望能够从一个随机丢失2个字母的单词生成空白填充

$word = "superman";

I would like to be able to randomly choose 2 letters from what ever word is in $word and build a fill in the blank box for me to be able to answer

example some how random picks the p and the a su_erm_n comes up so I would fill in the first box with p and the second one with a I guess with a form

$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n";

if ($wordfinshed == $word) {
echo "congrats";
}
else{
echo "try again";
}

I am just learning php I have some things that I have done that are very complicated but was having a hard time with the random stuff any help would help me learn this

  • 写回答

2条回答 默认 最新

  • douyueqing1530 2015-04-28 22:35
    关注

    You can use PHP's rand() function to select a random number from 0 to the length of the word you are modifying and change the character at that index to something else

    For example:

    $str = "superman";
    $str[rand(0, strlen($str)-1)] = "_";
    

    Assuming that the rand() function output a value of 3 for example, we'd end up with this output:

    sup_rman
    

    We can put this in a function that can be called more than once in order to make more than one blank space in the word:

    function addBlank($str){
        do{
            $index = rand(0, strlen($str)-1);
            $tmp = $str[$index];
            $str[$index] = "_";
        } while($tmp =! "_");
    
        return $str;
    }
    

    This function accepts a string and after each call will replace a letter in the string with _. Each call will result in one more blank space. The variable $tmp holds the value of the string at the randomly chosen index and checks that it wasn't already a blank space, and if it was, it picks another index to try to replace.

    So to put this in practice, we can call the above function multiple times and store the result back into a variable, here is example output:

    $str = addBlank("superman");
    //the value of $str is now sup_rman
    $str = addBlank($str)
    //the value of $str is now sup_r_an
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据