【发布时间】:2014-02-03 12:39:37
【问题描述】:
下面这句话
The boy is {good|better|best} in his {school|tution|class|scociety}
现在我需要创建一个递归 PHP 函数,它将这句话作为输入并输出如下:-
The boy is good in his school
The boy is good in his tution
以类似的方式,我需要创建 12 行,因为上面的句子有 12 个单词。如下:-
good with this 4 {school|tution|class|scociety}
better with this 4 {school|tution|class|scociety}
best with this 4 {school|tution|class|scociety}
为此,我尝试了以下方法:-
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 />';
}
但低于输出:-
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
有什么帮助吗?
【问题讨论】:
标签: php regex arrays random-sample