Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need to create an random sentence from a given sentence

with below sentence,

{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}

I need to create a random() function which will give below output:-

Please make this cool test sentence rotate fast and random.
OR
Just make this random test sentence spin and be random.

I'm not sure how will I do this.

I've tried below but didn't get result.

echo spinningFunction($str);

function spinningFunction($str)
{
    $output = "";
    $pattern = "/\[.*?\]|\{.*?\}/";
    preg_match_all($pattern, $str, $match);

    $arr = array_map(function($value){
        return explode("|", $value);
    }, $match[1]);


    foreach($arr[0] as $adj)
        foreach($arr[1] as $name)
            $output.= "{$adj} make this {$name} test sentence<br />";
    return $output;
}

any help please?

EDIT:-

function spinningFunction($str)
{
    $str = preg_replace_callback('/(\{[^}]*)([^{]*\})/im', "spinningFunction", $str);
    return $str;
}

Will someone help me to achieve an array like below from above sentence:-

Array
(
    [0] => Array
        (
            [0] => {Please|Just}
            [1] => {cool|awesome|random}
            [2] => {rotate {quickly|fast} and random|spin and be random}
        )
)
like image 879
Ripa Saha Avatar asked Jan 21 '26 05:01

Ripa Saha


1 Answers

Here's a solution that requires to use the syntax {a|[b|c]} for nested sets. It also only goes one level deep manually, so there is no clean/simple recursion. Depending on your use case, this could be fine though.

function randomizeString($string)
{
    if(preg_match_all('/(?<={)[^}]*(?=})/', $string, $matches)) {
        $matches = reset($matches);
        foreach($matches as $i => $match) {
            if(preg_match_all('/(?<=\[)[^\]]*(?=\])/', $match, $sub_matches)) {
                $sub_matches = reset($sub_matches);
                foreach($sub_matches as $sub_match) {
                    $pieces = explode('|', $sub_match);
                    $count = count($pieces);

                    $random_word = $pieces[rand(0, ($count - 1))];
                    $matches[$i] = str_replace('[' . $sub_match . ']',     $random_word, $matches[$i]);
                }
            }

            $pieces = explode('|', $matches[$i]);
            $count = count($pieces);

            $random_word = $pieces[rand(0, ($count - 1))];
            $string = str_replace('{' . $match . '}', $random_word, $string);
        }
    }

    return $string;
}

var_dump(randomizeString('{Please|Just} make this {cool|awesome|random} test sentence {rotate [quickly|fast] and random|spin and be random}.'));
// string(53) "Just make this cool test sentence spin and be random."

var_dump(randomizeString('You can only go two deep. {foo [bar|foo]|abc 123}'));
// string(33) "You can only go two deep. foo foo"
like image 134
Sam Avatar answered Jan 23 '26 21:01

Sam