i'm sure this is an easy one, but what would be the best way to randomize text from a string? something like:
$content = "{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..
asked Apr 20, 2011 at 20:49
john
1,3304 gold badges21 silver badges34 bronze badges
-
just an example. it's actually for randomizing articles.john– john2011年04月20日 20:57:42 +00:00Commented Apr 20, 2011 at 20:57
3 Answers 3
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);
answered Apr 20, 2011 at 20:54
Crozin
44.4k13 gold badges92 silver badges136 bronze badges
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 . "!";
answered Apr 20, 2011 at 20:58
Titus
4,6776 gold badges34 silver badges45 bronze badges
Comments
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);
}
?>
answered Apr 20, 2011 at 21:00
Dutchie432
29.3k20 gold badges94 silver badges110 bronze badges
Comments
lang-php