2016-09-12 15 views
2

bashブレースの拡張を実現するPHPの方法はありますか?例えばPHPのBashブレース拡張?

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

よう

[[email protected] ~]$ echo {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サーバー)

注:これはちょうど実行中のコマンドグループに関連するものなど、中括弧拡張の他の機能ではなく、文字列を出力するユースケース。

+0

入れ子にされたループを使うことはできますか?私はこれを行う組み込みのPHP関数を知らない。 –

+0

@CharlotteDunoisネストされたループについて考えましたが、bashが任意の数のブレース式を処理できるのに対して、ブレース式の数は事前に知っていなければならないようです。 – chiliNUT

+0

テキストを印刷するだけですか? – MoeinPorkamel

答えて

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

これはちょうど2つの括弧で囲まれた式を扱いますが、任意の数ではありません – chiliNUT

+0

@chiliNUTはコード – MoeinPorkamel

+0

に無制限ブレースサポートを追加しました。これはすばらしいです! ({{hello、hi} to my {仲間、敵}}は '私の友人にこんにちは私の敵にこんにちは私の敵に私の友人にこんにちは 'をもたらすはずですが、私は括弧の間の文字を考慮する私は自分自身でそれを理解することができると思う;これは素晴らしいスタートです。 – chiliNUT