2011-04-20 37 views
0

我相信這是一個容易的,但什麼是隨機化字符串文本的最佳方法?是這樣的:我如何隨機化一個字符串?

$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!"; 

我怎樣才能使輸出這樣的:

哎!我很好!
你好!我很好!
等。

+0

說話者的字符串,呃? – 2011-04-20 20:54:33

+0

只是一個例子。它實際上是爲隨機化文章。 – john 2011-04-20 20:57:42

回答

4

也許你可以試試:

$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!"; 

$randomOutput = preg_replace('/(\{.*?\})/s', function($matches) { 
    $possibilities = (array) explode('|', trim($matches[0], '{}')); 

    return $possibilities[array_rand($possibilities)]; 
}, $content); 

版本的PHP < 5.3

function randomOutputCallback($matches) { 
    $possibilities = (array) explode('|', trim($matches[0], '{}')); 

    return $possibilities[array_rand($possibilities)]; 
} 

$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!"; 

$randomOutput = preg_replace('/(\{.*?\})/s', 'randomOutputCallback', $content); 
+0

PHP> 5.3只。 – 2011-04-20 20:59:41

+0

謝謝你,我在5.1.6上試了一下。 @crozin可能是一個解決方案類似於較舊的PHP? – john 2011-04-20 21:04:21

+0

@john:我已經添加了舊版本的PHP的等價物。 – Crozin 2011-04-20 21:38:20

0

如果您使用數組:

$greeting = array("hey","hi","hello there"); 
$suffix = array("good","great"); 

$randGreeting = $greeting[rand(0, sizeof($greeting))]; 
$randSuffix = $suffix[rand(0,(sizeof($suffix)))]; 

echo "$randGreeting, I'm $randSuffix!"; 

當然,你也可以寫的最後一行是:

echo $randomGreeting . ", I'm " . $randSuffix . "!"; 
0

我會安排在一個陣列...像This Live Demo的元素。

<?php 

$responseText = array(
    array("hey","hi","hello there"), 
    "! ", 
    array("i am", "i'm"), 
    " ", 
    array("good", "great"), 
    "! " 
); 

echo randomResponse($responseText); 

function randomResponse($array){ 
    $result=''; 
    foreach ($array as $item){ 
     if (is_array($item)) 
      $result.= $item[rand(0, count($item)-1)]; 
     else 
      $result.= $item; 
    } 
    return ($result); 
} 
?>