php - I would like to be able to generate a fill in the blank from a word missing 2 letters randomly -
$word = "superman"; i able randomly choose 2 letters ever word in $word , build fill in blank box me able answer
example how random picks p , su_erm_n comes fill in first box p , second 1 guess form
$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n"; if ($wordfinshed == $word) { echo "congrats"; } else{ echo "try again"; } i learning php have things have done complicated having hard time random stuff me learn
you can use php's rand() function select random number 0 length of word modifying , change character @ index else
for example:
$str = "superman"; $str[rand(0, strlen($str)-1)] = "_"; assuming rand() function output value of 3 example, we'd end output:
sup_rman we can put in function can called more once in order make more 1 blank space in word:
function addblank($str){ do{ $index = rand(0, strlen($str)-1); $tmp = $str[$index]; $str[$index] = "_"; } while($tmp =! "_"); return $str; } this function accepts string , after each call replace letter in string _. each call result in 1 more blank space. variable $tmp holds value of string @ randomly chosen index , checks wasn't blank space, , if was, picks index try replace.
so put in practice, can call above function multiple times , store result variable, here example output:
$str = addblank("superman"); //the value of $str sup_rman $str = addblank($str) //the value of $str sup_r_an
Comments
Post a Comment