0

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
1
  • just an example. it's actually for randomizing articles. Commented Apr 20, 2011 at 20:57

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for that i was trying it on 5.1.6. @crozin maybe a solution similar for older php?
@john: I've added equivalent for older versions of PHP.
0

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.