Php 用多个单词完成一个句子
我有下面的句子Php 用多个单词完成一个句子,php,regex,arrays,random-sample,Php,Regex,Arrays,Random Sample,我有下面的句子 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 good with this 4 {school|tution|class|scociety} better with this 4 {schoo
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
good with this 4 {school|tution|class|scociety}
better with this 4 {school|tution|class|scociety}
best with this 4 {school|tution|class|scociety}
以类似的方式,我需要创建12行,因为上面的句子有12个单词。如下图所示:-
The boy is good in his school
The boy is good in his tution
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 />';
}
有什么帮助吗?您最好在正则表达式中稍作更改,然后使用
分解
将它们放入数组,然后使用循环打印出句子
<?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";
您的正则表达式模式给出以下输出:-数组([0]=>Array([0]=>{good | better | best}[1]=>{school | tution | class | scociety})[1]=>Array([0]=>good | better | best[1]=>school | tution | class | scociety])您应该使用:
/(?@SamSullivan我为什么要使用它?你会得到一个简单的数组,而不是多维数组,我认为这会使代码更可读(并可能节省微不足道的内存)。但我认为这没什么大不了的。@SamSullivan在这种情况下并不重要。