how do i randomize a string?
i'm sure this is an easy one, but what would be the best way to randomize text from a string? something like:
$co开发者_如何转开发ntent = "{hey|hi|hello there}! {i am|i'm} {good|great}!";
how can i make the output like this:
hey! i'm good!
hello there! i am great! etc..
Maybe try something like:
$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);
Version for 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);
If you use an array:
$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!";
Of course, you could also write the last line as:
echo $randomGreeting . ", I'm " . $randSuffix . "!";
I would arrange the elements in an array... Something like 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);
}
?>
精彩评论