【问题标题】:Hide word randomly from a sentence从句子中随机隐藏单词
【发布时间】:2014-08-30 16:54:09
【问题描述】:

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

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

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

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

【问题讨论】:

  • $removed_word = $words[array_rand($words)]; $words[array_rand($words)] = '___';
  • 这是返回“M”
  • 不确定你是如何运行它的。它对我有用:eval.in/185799
  • 是的,我搞砸了,谢谢

标签: php html


【解决方案1】:
$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

编辑:如果单词长度未知,则使其工作

【讨论】:

  • 打败我。很好的答案。
  • @DanDoNet 谢谢。 rand() 是我能想到的第一件事。
【解决方案2】:

你可以使用这样的东西

$word = explode(' ', $sentence);
$word = $word[rand(0, count($sentence) - 1)];

explode 函数在你想打断字符串时非常有用。还有一个函数 implode 正好相反

【讨论】:

    【解决方案3】:

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

    <?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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      相关资源
      最近更新 更多