我有下面的句子
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
有什么帮助吗?
答案 0 :(得分:3)
你最好在你的正则表达式中改变一点,然后用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 scociety