PHP-需要从给定的句子创建随机句子
作者:互联网
下面的句子,
{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}
我需要创建一个random()函数,该函数将提供以下输出:-
Please make this cool test sentence rotate fast and random.
OR
Just make this random test sentence spin and be random.
我不确定该怎么做.
我在下面尝试过,但没有得到结果.
echo spinningFunction($str);
function spinningFunction($str)
{
$output = "";
$pattern = "/\[.*?\]|\{.*?\}/";
preg_match_all($pattern, $str, $match);
$arr = array_map(function($value){
return explode("|", $value);
}, $match[1]);
foreach($arr[0] as $adj)
foreach($arr[1] as $name)
$output.= "{$adj} make this {$name} test sentence<br />";
return $output;
}
有什么帮助吗?
编辑:-
function spinningFunction($str)
{
$str = preg_replace_callback('/(\{[^}]*)([^{]*\})/im', "spinningFunction", $str);
return $str;
}
有人可以从上面的句子中帮助我实现如下数组吗?
Array
(
[0] => Array
(
[0] => {Please|Just}
[1] => {cool|awesome|random}
[2] => {rotate {quickly|fast} and random|spin and be random}
)
)
解决方法:
这是一个需要对嵌套集使用语法{a | [b | c]}的解决方案.手动也只能深入一层,因此没有干净/简单的递归.根据您的用例,这可能会很好.
function randomizeString($string)
{
if(preg_match_all('/(?<={)[^}]*(?=})/', $string, $matches)) {
$matches = reset($matches);
foreach($matches as $i => $match) {
if(preg_match_all('/(?<=\[)[^\]]*(?=\])/', $match, $sub_matches)) {
$sub_matches = reset($sub_matches);
foreach($sub_matches as $sub_match) {
$pieces = explode('|', $sub_match);
$count = count($pieces);
$random_word = $pieces[rand(0, ($count - 1))];
$matches[$i] = str_replace('[' . $sub_match . ']', $random_word, $matches[$i]);
}
}
$pieces = explode('|', $matches[$i]);
$count = count($pieces);
$random_word = $pieces[rand(0, ($count - 1))];
$string = str_replace('{' . $match . '}', $random_word, $string);
}
}
return $string;
}
var_dump(randomizeString('{Please|Just} make this {cool|awesome|random} test sentence {rotate [quickly|fast] and random|spin and be random}.'));
// string(53) "Just make this cool test sentence spin and be random."
var_dump(randomizeString('You can only go two deep. {foo [bar|foo]|abc 123}'));
// string(33) "You can only go two deep. foo foo"
标签:random-sample,php,regex,function 来源: https://codeday.me/bug/20191122/2058190.html