【问题标题】:PHP Spintax return array with all possibilitiesPHP Spintax 返回具有所有可能性的数组
【发布时间】:2013-05-19 07:06:20
【问题描述】:

我有一个字符串:{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!

我想知道是否有人可以通过一个函数来帮助我,该函数将返回一个包含所有可能性的数组?或者至少提供有关如何获取它们以及使用哪些 PHP 函数的逻辑?

谢谢

【问题讨论】:

  • 我相信 var_dumpprint_r 会给你想要的数组,除非我完全误解了你的问题。

标签: php spintax


【解决方案1】:

嵌套foreach 循环。

foreach($greetings as greeting)
    foreach($titles as title)
        foreach($names as $name)
            echo $greeting,' to you, ',$title,' ',$name;

您可以通过预先对数组进行排序并更改前三行的顺序来调整它们出现的顺序

更新

这是我使用递归函数想到的

假设您使用正则表达式将您的数据放在类似这样的地方,然后展开这应该很简单:

$data = array(
    array("Hello","Howdy","Hola"),
    array(" to you, "),
    array("Mr.", "Mrs.", "Ms."),
    array(" "),
    array("Smith","Williams","Austin"),
    array("!")
);

现在是函数

function permute(&$arr, &$res, $cur = "", $n = 0){

    if ($n == count($arr)){
        // we are past the end of the array... push the results
        $res[] = $cur;
    } else {
                    //permute one level down the array
        foreach($arr[$n] as $term){
            permute($arr, $res, $cur.$term, $n+1);
        }
    }
}

这是一个调用示例:

$ret = array();
permute($data, $ret);
print_r($ret);

产生输出

    Array
(
    [0] => Hello to you, Mr. Smith!
    [1] => Hello to you, Mr. Williams!
    [2] => Hello to you, Mr. Austin!
    [3] => Hello to you, Mrs. Smith!
    [4] => Hello to you, Mrs. Williams!
    [5] => Hello to you, Mrs. Austin!
    [6] => Hello to you, Ms. Smith!
    [7] => Hello to you, Ms. Williams!
    [8] => Hello to you, Ms. Austin!
    [9] => Howdy to you, Mr. Smith!
    [10] => Howdy to you, Mr. Williams!
    [11] => Howdy to you, Mr. Austin!
    [12] => Howdy to you, Mrs. Smith!
    [13] => Howdy to you, Mrs. Williams!
    [14] => Howdy to you, Mrs. Austin!
    [15] => Howdy to you, Ms. Smith!
    [16] => Howdy to you, Ms. Williams!
    [17] => Howdy to you, Ms. Austin!
    [18] => Hola to you, Mr. Smith!
    [19] => Hola to you, Mr. Williams!
    [20] => Hola to you, Mr. Austin!
    [21] => Hola to you, Mrs. Smith!
    [22] => Hola to you, Mrs. Williams!
    [23] => Hola to you, Mrs. Austin!
    [24] => Hola to you, Ms. Smith!
    [25] => Hola to you, Ms. Williams!
    [26] => Hola to you, Ms. Austin!
)

【讨论】:

  • 感谢 Orangepill,但这是有限的。而且我什至不知道 { | 有多少组合。 } 我会得到。可以是 10、100 :)
  • 从我可以通过互联网阅读的内容来看,我可能需要一些排列。我发现了几个很好的置换函数,不要只知道如何将它们与那个字符串结合起来
  • @raul - 所有的可能性?您发布的内容看起来像文章在旋转。在这种情况下,您不需要所有的可能性。您只需要在每组括号内随机选择一个项目。
  • 是的,这就像文章旋转。但我想要所有的可能性。该项目有点不同。我有纺纱课,效果很好。我只是不知道如何编写或更改内容以给我所有数组,而不是 1 个随机行。
  • 啊,也许要提到我并不真正关心嵌套的一个,比如 { hello {x|y},你好吗|good day {x|y} !} 我只关心实际上是 1 级:)
【解决方案2】:

我知道有点晚了,但如果你还在寻找更好的解决方案,你可以看看这个:ChillDevSpintax

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2015-11-17
    • 2018-12-22
    • 2018-04-30
    相关资源
    最近更新 更多