PHP Spintax返回所有可能性的数组

时间:2013-05-19 07:06:21

标签: php spintax

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

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

谢谢

2 个答案:

答案 0 :(得分:0)

嵌套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!
)

答案 1 :(得分:0)

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