从php的字典中生成随机单词


Generate random word from the dictionary in php

请查看此链接:字典中的随机条目

这个例子是C#,然而,我的问题是如何从php中的字典生成一个随机条目?

php有一个内置的字典功能,还是我需要一个API或其他东西来做这个?

您可以从GitHub下载包含每行所有字典单词的文本文件。在PHP教程

中从英文字典中获取随机单词

下面是随机选择一行并获取该行单词的PHP代码:

<?php
$file = "words_alpha.txt";
$file_arr = file($file);
$num_lines = count($file_arr);
$last_arr_index = $num_lines - 1;
$rand_index = rand(0, $last_arr_index);
$rand_text = $file_arr[$rand_index];
echo $rand_text;
?>

来源:从PHP的英文字典中获取随机单词

array_rand可能会做你想要的,如果我理解正确的话。

$array = array(
    'key' => 'value',
    'key2' => 'value2',
    // etc
);
$randomKey = array_rand($array); // get a random key
echo $array[$randomKey]; // get the corresponding value

只是为了完成Tom的回答,我在我的一个项目中也有类似的需求,这里我的类的棘手特性是字典直接嵌入到PHP文件中。

/**
 * Generate bunch of english Lorem Ipsum.
 * 
 * 
 * 
 * @category Tool
 * @package Tool
 * @version 
 */
class RandomWord
{
    /**
     * List of words in the dictionnary 
     * 
     * @var array
     */
    static private $_words = array();
    /**
     * Load the dictionary. 
     * 
     * This would load the dictionnary embedded in this PHP file
     */
    static public function loadDictionnary()
    {
        $fp = fopen(__FILE__, 'r');
        $halted = false;
        while (($line = fgets($fp, 4096)) !== false) {
            if ($halted == false) {
                if (preg_match('/__halt_compiler'(');/', $line)) {
                    $halted = true;
                }    
            } else {
                list($word, $dummy) = explode("'t", $line);
                array_push(self::$_words, $word);    
            }
        }
        fclose($fp);
    }
    /**
     * Pickup a random word from the dictionnary
     * 
     * @return string
     */
    static public function random()
    {
        if (!count(self::$_words)) {
            self::loadDictionnary();
        }
        return self::$_words[array_rand(self::$_words)];
    }
    /**
     * Generate a number of paragraph of random workds 
     * 
     * @param integer $numberOfWords
     * @param integer $paragraph
     * @return string
     */
    static public function loremIpsum($numberOfWords = 20, $paragraph = 1)
    {
        $ret = '';
        for ($i = 0; $i < $paragraph; $i++) {
            for ($v = 0; $v < $numberOfWords; $v++) {
                $ret .= self::random() . ' ';
            }
            if ($paragraph > 1) {
                $ret .= "'n";
            }
        }
        $ret = substr($ret, 0, strlen($ret) - 1);
        return $ret;
    }
}
__halt_compiler();
's gravenhage   |h
'tween  |v
'tween decks    |v
.22 |N
0   |NA
1   |NA
1-dodecanol |N
1-hitter    |N
10  |NA
100 |NA
1000    |NA
10000   |N
100000  |N
1000000 |N
1000000000  |N
1000000000000   |N
1000th  |A
100th   |A
10th    |A
11  |NA
11-plus |N