在PHP中使用Bash大括号扩展?

时间:2016-09-12 16:22:15

标签: php bash

有没有完成bash大括号扩展的php方法?例如

[chiliNUT@server ~]$ echo {hello,hi,hey}\ {friends,world},
hello friends, hello world, hi friends, hi world, hey friends, hey world,

类似

<?php
echo brace_expand("{hello,hi,hey} {friends,world}");
//hello friends, hello world, hi friends, hi world, hey friends, hey world,

目前我正在使用

<?php
echo shell_exec("echo {hello,hi,hey}\ {friends,world}");

但它似乎不是正确的方法(并且可能无法在Windows服务器上运行)

注意这仅适用于打印字符串的用例,而不是大括号扩展的任何其他功能,例如与运行命令组相关的功能。

1 个答案:

答案 0 :(得分:1)

这应该可以完成你的工作(你可以改进它):

<?php

function brace_expand($string)
{
    preg_match_all("/\{(.*?)(\})/", $string, $Matches);

    if (!isset($Matches[1]) || !isset($Matches[1][0]) || !isset($Matches[1][1])) {
        return false;
    }

    $LeftSide = explode(',', $Matches[1][0]);
    $RightSide = explode(',', $Matches[1][1]);

    foreach ($LeftSide as $Left) {
        foreach ($RightSide as $Right) {
            printf("%s %s" . PHP_EOL, $Left, $Right);
        }
    }
}

brace_expand("{hello,hi,hey} {friends,world}");

输出:

hello friends
hello world
hi friends
hi world
hey friends
hey world

编辑:无限大括号支持

<?php

function brace_expand($string)
{
    preg_match_all("/\{(.*?)(\})/", $string, $Matches);

    $Arrays = [];

    foreach ($Matches[1] as $Match) {
        $Arrays[] = explode(',', $Match);
    }

    return product($Arrays);
}

function product($a)
{
    $result = array(array());
    foreach ($a as $list) {
        $_tmp = array();
        foreach ($result as $result_item) {
            foreach ($list as $list_item) {
                $_tmp[] = array_merge($result_item, array($list_item));
            }
        }
        $result = $_tmp;
    }
    return $result;
}

print_r(brace_expand("{hello,hi,hey} {friends,world} {me, you, we} {lorem, ipsum, dorem}"));