2012-12-30 35 views
0

我想在每行前添加一個隨機的文字,像這樣:隨機字在文件每行前面

前:

One 
Two 
Three 

後:

Love One 
My Two 
Other Three 

更新: 對不起,我的意思是'before'文本是textarea提交的文本,所以它的$ _POST值和我想要的結果'後'文本。簡單來說,代碼如下: 假設前面的文本是在$ _POST ['message']下的值,並且我想要echo這個值,但是在它前面有隨機文本。

我嘗試這一點,但僅適用於第一線的工作,而不是其他行:

$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 

感謝

+4

你從哪裏採購此文? – esqew

+0

我不明白你的問題。 –

+0

什麼樣的隨機?你可以從數組中獲得一個隨機文本,並且你可以從自動生成的文本中隨機取出一個文本?所以你需要什麼類型? –

回答

1

設置你想要的文字在一個陣列,並與您的陣列呼籲rand()函數元素鍵,然後打印元素 例如

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

你有array_rand()這樣的東西。 –

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 />"; 
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"; 
}