我相信这是一个容易的,但什么是随机化字符串文本的最佳方法?是这样的:我如何随机化一个字符串?
$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!";
我怎样才能使输出这样的:
哎!我很好!
你好!我很好!
等。
我相信这是一个容易的,但什么是随机化字符串文本的最佳方法?是这样的:我如何随机化一个字符串?
$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!";
我怎样才能使输出这样的:
哎!我很好!
你好!我很好!
等。
也许你可以试试:
$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);
如果您使用数组:
$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 . "!";
我会安排在一个阵列...像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);
}
?>
说话者的字符串,呃? – 2011-04-20 20:54:33
只是一个例子。它实际上是为随机化文章。 – john 2011-04-20 20:57:42