Complete the sentence with multiple words

I have below phrases

The boy is {good|better|best} in his {school|tution|class|scociety}

Now I need to create a recursive PHP function that will take this sentence as input and output as below: -

The boy is good in his school
The boy is good in his tution

Similarly, I need to create 12 lines, because the sentence above has 12 words. As shown below: -

good with this 4 {school|tution|class|scociety}

better with this 4 {school|tution|class|scociety}

best with this 4 {school|tution|class|scociety}

for this I try to do the following: -

function get_random($matches)
{
    $part     = substr($matches[0], 1, strlen($matches[0])-2);
    $part     = show_randomized($part);
    $rand     = array_rand($split = explode("|", $part));
    return $split[$rand];
}

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

// Test

$rand_sentence = "The boy is {good|better|best} in his {school|tution|class|scociety}";

for ($i = 0; $i < 10; $i++)
{
    echo show_randomized($rand_sentence).'<br />';
}

But getting below output: -

The boy is best in his tution
The boy is better in his school
The boy is good in his tution
The boy is better in his school
The boy is better in his scociety
The boy is best in his tution
The boy is better in his class
The boy is good in his school
The boy is best in his tution
The boy is best in his school

any help please?

+4
source share
1 answer

You'd better swap a little in your Regex, then use explodeto put them in an array, and then use loops to print the sentences.

<?php
    $str = "The boy is {good|better|best} in his {school|tution|class|scociety}";
    preg_match_all("/\{([^}]+)\}/", $str, $match);
    $arr = array_map(function($value){
        return explode("|", $value);
    }, $match[1]);
    foreach($arr[0] as $adj)
        foreach($arr[1] as $name)
            echo "The boy is {$adj} in his {$name}\n";

Exit

The boy is good in his school
The boy is good in his tution
The boy is good in his class
The boy is good in his scociety
The boy is better in his school
The boy is better in his tution
The boy is better in his class
The boy is better in his scociety
The boy is best in his school
The boy is best in his tution
The boy is best in his class
The boy is best in his scociety
+3
source

All Articles