chiliNUT chiliNUT - 2 months ago 18
PHP Question

Bash brace expansion in php?

Is there a php way of accomplishing bash brace expansion? For example

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


something like

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


Currently I am using

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


But it does not seem like the correct way to go about it (and probably wouldn't work on a windows server)

NOTE that this is just for the use case of printing a string, not any of the other features of brace expansion such as those related to running groups of commands.

Answer

This should do the job in your case ( and you can improve it ):

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

Output:

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

Edit: unlimited brace support

<?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}"));
Comments