我确定这很简单,但是从字符串中随机化文本的最佳方法是什么?类似的东西:
$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!";
我怎么能这样输出:
哎!我很好! 你好!我很棒! 等。
答案 0 :(得分: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);
答案 1 :(得分: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 . "!";
答案 2 :(得分: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);
}
?>