【问题标题】:PHP Spintax ProcessorPHP Spintax 处理器
【发布时间】:2012-11-20 18:26:16
【问题描述】:

我一直在使用递归 SpinTax 处理器,如 here 所示,它适用于较小的字符串。但是,当字符串超过 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 似乎是这里的解决方案,但我不知道如何实现它并且具有更高效的性能。

谢谢!

【问题讨论】:

    标签: php regex string spintax


    【解决方案1】:

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

    // 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}.");
    

    【讨论】:

    • 非常感谢!正如马达拉的答案中所说的那样,这使我从内存错误到 .0002590 秒来处理一个 40KB 的文件。惊人的!谢谢
    【解决方案2】:

    您可以使用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);
    

    【讨论】:

    • 我喜欢这个解决方案。运行它需要 0.0002592 秒,而旧方法出现 Allowed memory size of 134217728 bytes exhausted (tried to allocate 74087 bytes) 错误。太棒了!
    • 我真的很感激这个答案——它真的很有帮助。然而,乔纳森·桑普森(Johnathan Sampson)首先做到了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 2010-10-27
    相关资源
    最近更新 更多