john
john

Reputation: 1330

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:

$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..

Upvotes: 0

Views: 147

Answers (3)

Crozin
Crozin

Reputation: 44406

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);

Upvotes: 4

Dutchie432
Dutchie432

Reputation: 29170

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);
}
?>

Upvotes: 0

Titus
Titus

Reputation: 4637

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 . "!";

Upvotes: 0

Related Questions