Reputation: 2540
I have below sentence
The boy is {good|better|best} in his {school|tution|class|scociety}
Now I need to create a recursive PHP function which will take this sentence as input and will output like below:-
The boy is good in his school
The boy is good in his tution
In similar way I need to create 12 lines, because the above sentence has 12 words. Like 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've tries below:-
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?
Upvotes: 4
Views: 113
Reputation: 48721
You'e better change a little in your Regex, then use explode
to put them in an array, then using loops to print out 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";
Output:
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
Upvotes: 3