我有下面的句子
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有什么帮助吗?
发布于 2014-01-15 07:15:41
您最好在Regex中稍微修改一下,然后使用explode将它们放在数组中,然后使用循环来打印句子。
<?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";输出
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 scocietyhttps://stackoverflow.com/questions/21130739
复制相似问题