PHP文本随机显示 rand display text
本代码实现功能,随机显示一文本文档中的代码行。其中文本文件内容注意:一行显示一条完整内容不要有回车,不能有半角的“引号”。文本名称:
yanyu.txt
内容范例
内容范例
A bad beginning makes a bad ending. 恶其始者必恶其终。 A bad bush is better than the open field. 有胜于无。 A bad compromise is better than a good lawsuit. 吃亏的和解也比胜诉强。 A bad conscience is a snake in one’s heart. 做贼心虚。 A bad custom is like a good cake, better broken than kept. 坏习惯像鲜馅饼,分食要比保存好。
<?php
//随机显示一条谚语;
$file = "yanyu.txt"; //存放谚语的文件位置;
//$refresh = 60; //刷新的时间间隔;
$data = file($file); //将文件存放在一个数组中;
$num = count($data); //谚语的条数;
$id = mt_rand(0,$num-1); //随机数字;
$text = chop($data[$id]); //显示第几行数据,并去除空格;
echo $text;
?>
<?php
/**
* 随机显示字符串的PHP函数
*
* @param 随机字符串的个数 $num
* @param 候选的字符串 $string
* @return 指定位数的字符串
*/
function randStr($num=5,$string=”){
if (!$string)//如果没有指定的字符串,候选字符串则是大小写字母和数字;
$string=’ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890′;
for($i=0;$i<$num;$i++){
$order = rand(0,strlen($string)-1);
$rand_string .= $string[$order];
}
return $rand_string;
}
//显示默认的随机字符:
echo randStr();
?>