从句子中随机隐藏单词

时间:2014-08-30 16:54:09

标签: php html

我有一句话,我想随机隐藏一个单词,例如:

<?php
$sentence = 'My name is Abu Rayane';
?>

如何隐藏该句子中的单词并将其替换为输入文本,以便用户可以填写它,然后检查单词是否正确?例如:

My name is Abu <input type="text" name="fillBlank"> <br />
<input type="submit" name="check" value="check">

3 个答案:

答案 0 :(得分:3)

$sentence = 'My name is Abu Rayane';
$sentence = explode(' ', $sentence); 
$position = rand(0, count($sentence) - 1);
$answer = $sentence[$position];
$sentence[$position] = '<input type="text" name="fillBlank">';
echo implode(" ", $sentence);

示例:https://eval.in/185829

编辑:如果未知单词的长度

,则使其有效

答案 1 :(得分:1)

你可以使用这样的东西

$word = explode(' ', $sentence);
$word = $word[rand(0, count($sentence) - 1)];
如果你想打破一个字符串,

explode函数真的很有用。还有函数implode,它完全相反

答案 2 :(得分:0)

我试过了,我从你的不同代码中得到了答案:

<?php
$sentence = 'My name is Abu Rayane';
$countSentence = str_word_count($sentence);

echo 'Total words '.$countSentence.'<br />';

// get random number from 0 to 4
$rand = rand(0, $countSentence - 1);

// explode sentence
$ex = explode(' ',$sentence);

// get the equivalent word for a rand number
$hide = $ex[$rand];

$z = implode(' ', $ex).'<br />';
echo str_replace($hide, '______', $z);
?>

经过测试:https://eval.in/185847