как я рандомизирую строку? - PullRequest
0 голосов
/ 21 апреля 2011

Я уверен, что это легко, но как лучше всего рандомизировать текст из строки? что-то вроде:

$content = "{hey|hi|hello there}! {i am|i'm} {good|great}!";

как мне сделать вывод следующим образом:

эй! я в порядке!
Привет! я великолепен!
и т.д ..

Ответы [ 3 ]

4 голосов
/ 21 апреля 2011

Может быть попробовать что-то вроде:

$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 </p>

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);
0 голосов
/ 21 апреля 2011

Я бы упорядочил элементы в массиве ... Что-то вроде Это 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);
}
?>
0 голосов
/ 21 апреля 2011

Если вы используете массив:

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