【问题标题】:How do I make it randomly display one item from the array in PHP?如何让它随机显示 PHP 数组中的一项?
【发布时间】:2013-02-21 06:10:53
【问题描述】:

我试图让它在输入$hello 中的一个单词时随机选择一个单词$bye 并显示它。在我尝试它的那一刻,它只显示 0、1 或 2。我该如何解决这个问题,所以它会随机给我一个来自 $bye 数组的单词。

<?php
$words = $_POST['words'];
$hello = array('hello', 'hi', 'yo', 'sup');
$bye = array('bye', 'seeya', 'aurevoir');
$words = preg_replace('/\b('.implode('|', $hello).')\b/i', '<span class="highlight">'.array_rand($bye).'</span>', $words);
echo $words;
?>

【问题讨论】:

  • 抱歉,目前无法为这个问题做出贡献。请在上面编辑您的问题并使细节更清楚。特别是使用内置编辑器功能以可读的方式发布您当前的代码来格式化代码。当前的代码 sn -p 是不够足够的。

标签: php arrays random


【解决方案1】:
$index = array_rand($bye);
echo $bye[$index];

【讨论】:

    【解决方案2】:
    $hello = array("Hi", "Hola", "Yo dawg! I heard you liked words in your hello!");
    $bye = array("Later","Hasta Luego","Guten Tag");
    echo $bye[array_rand($hello)];
    

    【讨论】:

      【解决方案3】:

      我没有清楚地理解你的问题,如果你想从$word 数组中选择一个随机项,如果$word$hello 数组中,试试这个:

      $hello = array('hello', 'hi', 'yo', 'sup');
      $bye = array('bye', 'seeya', 'aurevoir');
      if(in_array($word,$hello))
          echo $bye[array_rand($bye)];
      else
          echo "word is not in hello array";
      

      【讨论】:

        【解决方案4】:

        您可以将数组与 preg_replace 一起使用

        $words="this is any text bye";
        $bye = array('/bye/', '/seeya/', '/aurevoir/'); //pattern
        
        $hello=array('hello', 'hi', 'yo');  //$replacements
        shuffle($hello);
        
        echo preg_replace($bye, $hello, $words);
        

        【讨论】:

          猜你喜欢
          • 2018-10-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 2017-01-12
          • 2015-07-31
          • 1970-01-01
          相关资源
          最近更新 更多