gpt4 book ai didi

php - 需要根据给定的句子创建一个随机句子

转载 作者:搜寻专家 更新时间:2023-10-31 20:41:12 27 4
gpt4 key购买 nike

用下面的句子,

{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"

关于php - 需要根据给定的句子创建一个随机句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155392/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com