文件中每行前面的随机单词

时间:2012-12-30 17:02:48

标签: php file random

我想在每行前面添加一个随机文本,如下所示:

在:

One
Two
Three

后:

Love One
My Two
Other Three

更新: 抱歉混淆,我的意思是'之前'文本是一个textarea提交的文本,所以它在$ _POST值,我希望结果像'后'文本。简单来说,代码如下: 假设前一个文本在$ _POST ['message']值下,我希望回显该值,但前面有随机文本。

我尝试这个但只适用于第一行而不是另一行:

$rand = array("Love", "My", "Other");
$message = trim(@$_POST['message']) ;
$message = str_replace(" ","+",$message);//Convert the space to +
$modifiedTextAreaText = str_replace( "\n", "\n$rand", $message);//This One Not Working
echo $rand[array_rand($rand, 1)]. $modifiedTextAreaText ;//This one working only for the first line

由于

3 个答案:

答案 0 :(得分:2)

你的意思是这样的:

<?php

$randomWords = array('Love', 'My', 'Other');

$randomKey = array_rand($randomWords, 1);
echo $randomWords[$randomKey] . " One<br />";

$randomKey = array_rand($randomWords, 1);
echo $randomWords[$randomKey] . " Two<br />";

$randomKey = array_rand($randomWords, 1);
echo $randomWords[$randomKey] . " Three<br />";

答案 1 :(得分:2)

您可以构建数组,然后随机播放两者或只是随机化的数组。然后结合两者。

<?php
$rands = array("Love", "My", "Other");
shuffle($rands);
$words = array("One", "Two", "Three");
$new = array_combine($rands, $words);

foreach($new as $key => $val){
    echo "$key $val<br />\n";
}

答案 2 :(得分:1)

在数组中设置所需的文本,并使用数组元素键调用rand()函数,然后打印元素 示例

$text = array( 0=> "text0", 1=> "text1", 2=> "text2");
$randomtext = rand (0,2);
echo $text['$randtext'];