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

标签 php regex function random

用下面的句子,

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

相关文章:

regex - 如何使用正则表达式捕获和替换包含单独模式的行上的所有模式

javascript - (?=正则表达式) VS (? :regex)

c++ - 在指定其他参数时使用前导参数的默认值

c - 为什么指针需要在其参数中使用地址运算符来修改结构成员的值?

php - mysql_num_rows 在第二个查询中返回 0

PHP 计算立方根 x^(1/3) 不起作用

PHP MySQL - 从复选框获取数据

c# - 从结果中的字符串中排除重复项

php - 验证删除帖子功能?

php - 如何将外部数据库(xampp)中的 listView 填充到 fragment 中?