2016-09-12 5 views
2

bash 중괄호 확장을 수행하는 PHP 방법이 있습니까? 예를 들어 나는 PHP에서 Bash 중괄호 확장?

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

을 사용하고

[[email protected] ~]$ 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, 

처럼하지만 그것에 대해 이동하는 올바른 방법은 아닌 것 같아 (아마에 작동하지 않을 것입니다 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 {friends, enemies} '는 내 친구들에게 안녕하세요, 내 원수에게 안부를 줘야합니다. 나는 내 스스로 그것을 알아낼 수 있다고 생각한다; 이것은 환상적인 출발점이다. – chiliNUT