PHP Spintax处理器

Dav*_*vid 5 php regex string spintax

我一直在使用这里看到的recurisve SpinTax处理器,它适用于较小的字符串.但是,当字符串超过20KB时,它开始耗尽内存,这就成了一个问题.

如果我有这样的字符串:

{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!
Run Code Online (Sandbox Code Playgroud)

我希望将这些单词的随机组合放在一起,而不是使用上面链接中所见的技术(通过字符串递归直到花括号中没有更多的单词),我应该怎么做?

我在考虑这样的事情:

$array = explode(' ', $string);
foreach ($array as $k=>$v) {
        if ($v[0] == '{') {
                $n_array = explode('|', $v);
                $array[$k] = str_replace(array('{', '}'), '', $n_array[array_rand($n_array)]);
        }
}
echo implode(' ', $array);
Run Code Online (Sandbox Code Playgroud)

但是当spintax的选项之间存在空格时,它就会崩溃.RegEx似乎是这里的解决方案,但我不知道如何实现它具有更高效的性能.

谢谢!

Sam*_*son 6

您可以创建一个使用回调函数来确定将创建和返回多个潜在变量的函数:

// Pass in the string you'd for which you'd like a random output
function random ($str) {
    // Returns random values found between { this | and }
    return preg_replace_callback("/{(.*?)}/", function ($match) {
        // Splits 'foo|bar' strings into an array
        $words = explode("|", $match[1]);
        // Grabs a random array entry and returns it
        return $words[array_rand($words)];
    // The input string, which you provide when calling this func
    }, $str);
}

random("{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!");
random("{This|That} is so {awesome|crazy|stupid}!");
random("{StackOverflow|StackExchange} solves all of my {problems|issues}.");
Run Code Online (Sandbox Code Playgroud)