6

我一直在使用 recurisve SpinTax 处理器,如此处所示它适用于较小的字符串。但是,当字符串超过 20KB 时,它开始耗尽内存,这成为一个问题。

如果我有这样的字符串:

{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!

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

我在想这样的事情:

$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);

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

谢谢!

4

2 回答 2

7

您可以创建一个函数,该函数在其中使用回调来确定将创建和返回许多潜力的哪个变体:

// 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}.");
于 2012-11-20T18:36:48.520 回答
3

您可以使用preg_replace_callback()来指定替换功能。

$str = "{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!";

$replacement = function ($matches) {
    $array = explode("|", $matches[1]);
    return $array[array_rand($array)];
};

$str = preg_replace_callback("/\{([^}]+)\}/", $replacement, $str);
var_dump($str);
于 2012-11-20T18:43:01.060 回答