How to Shuffle and Echo 3 Random Words out of a String?

泪湿孤枕 提交于 2019-12-08 03:10:29

问题


a question about getting some random words out of a bigger string after it has been translated:

<?=__("water, chicken, banana, rice, bread, salt, cucumber, ananas, peach")?>

on my site currently outputs:

water, kip, banaan, rijst, zout, komkommer, ananas, perzik

now imagine I want to get just 3 words from that on random. How do I do that?

It's important not to touch the words parts inside __(" & ") part! The translater cannot process when __($var) but ONLY when __("word1, word2, word3").

I imagine the best is to first put the the outcome into a string or array (this is how far I came please don't laugh)

$translated = __("water, chicken, banana, rice, bread, salt, cucumber");
echo $translated;
# shuffle & echo 3 items

How do I proceed from here to randomly get 3 words out of $entireString ?

update

    $array = explode(',', $translated);
    $randomKeys = array_rand($array, 3);
    $translated = '';
    foreach(array_keys($randomKeys) as $key){
      $translated .= $array[$key].' ';  // use space or comma
    }

    echo $translated;

echos: water kip banaan always. so it does not seem to shuffle well?


回答1:


you can use

$array = explode(',', $str);
$randomKeys = array_rand($array, 3);
$str = '';
foreach($randomKeys as $key){
  $str .= $array[$key].' ';  // use space or comma
}



回答2:


function randomstr($str, $num = 3) {
   $str = explode(',', $str);
   return implode(',' array_rand($array, $num));
}

Now:

<?=__(randomstr("water, chicken, banana, rice, bread, salt, cucumber, ananas, peach"))?>

Or in function __:

function __($string) {
   $string = randomstr($string);
   // more your code
}



回答3:


Would it be possible to store the values not as string, but as an array? If you cant just explode them by , then get a random element from the array and translate that one.

For example:

$translated = __("water, soup, rice, peanutbutter");
$translatedWords = explode(',',$translated);
shuffle($translatedWords); //Randomize them

Would output something like Soep, Rijst, Pindakaas, Water

(Also __ is quite an odd name for a function)



来源:https://stackoverflow.com/questions/5155166/how-to-shuffle-and-echo-3-random-words-out-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!