2013-06-20 4 views
1

В начале я искал возможность опубликовать регулярное выражение в строке и затем сделать все возможные комбинации. Чтобы hallo [A-B] создал halloA и halloB. но мне кажется, что это невозможно (Regular expression listing all possibilities)динамические заполнители в строке php

Так что теперь я пытаюсь создать Somthing, который может Генделя:

[A-Z] 
[a-z] 
[0-9] 

Но я ничего не могу найти полезную.

Я также нашел это (PHP dynamic creation of alphabet), но это не то, что я ищу.

вход:

test[A-B][0-1][x-z] 

выход:

testA0x 
testA1x 
testA0y 
testA1y 
testB0x 
testB1x 
testB0y 
testB1y 

Мой сделал класс, который работал для меня:

<?php 

class parser { 
    private $groups; 
    private $result; 

    public function getGroups(){ 
     return $this->groups; 
    } 
    public function getResult(){ 
     return $this->result; 
    } 

    public function parse($text) 
    { 
     // Find each character group: [...] 
     preg_match_all('/(.*?)(?:\[([^[\]]{1,30})\]|$)/s', $text, $matches, PREG_SET_ORDER); 
     $groups = array(); 
     foreach ($matches as $match) { 
      if (!empty($match[1])) { 
       // Prefix: foo 
       $groups[] = $match[1]; 
      } 
      if (!empty($match[2])) { 
       // Group: [a-z0-9] 
       // For each range, add the chars to an array. ['a', 'b', ..., 'z', '0', ..., '9'] 
       $chrs = array(); 
       preg_match_all('/(.)(?:-(.))?/', $match[2], $ranges, PREG_SET_ORDER); 
       foreach ($ranges as $rng) 
       { 
        if (empty($rng[2])) { 
         $chrs[] = $rng[1]; 
        } 
        else { 
         $chrs = array_merge($chrs, range($rng[1], $rng[2])); 
        } 
       } 
       $groups[] = $chrs; 
      } 
     } 

     $this->groups = $groups; 
     return $groups; 
    } 

    public function permute($groups, $index = 0) 
    { 
     $result = array(); 
     if ($index >= count($groups)) 
     { 
      // Reached the end. Return a single, empty result. 
      $result[] = ''; 
     } 
     else if (is_string($groups[$index])) 
     { 
      // Current group is a simple string. Prepend it to all tail results. 
      $prefix = $groups[$index]; 
      foreach ($this->permute($groups, $index+1) as $s) 
      { 
       $result[] = $prefix . $s; 
      } 
     } 
     else { 
      // Otherwise it is an array of characters. Prepend each to every tail result. 
      $chars = $groups[$index]; 
      foreach ($this->permute($groups, $index+1) as $s) 
      { 
       foreach ($chars as $ch) { 
        $result[] = $ch . $s; 
       } 
      } 
     } 

     $this->result = $result; 
     return $result; 
    } 
} 
$text = 'test[A-BXZ][0-1][x-z]foo'; 
$parser = new parser(); 

$groups = $parser->parse($text); 
print_r($groups); 

$permutations = $parser->permute($groups); 
print_r($permutations); 

?> 
+0

Вы проверили [это] (http://stackoverflow.com/q/1248519/1578604)? – Jerry

+0

@jerry tnx я этого не видел, но я забыл о том, что для PHP извините! –

+0

Итак, можете ли вы конкретно отредактировать свой вопрос, предоставляя вход и ожидаемый результат? Непонятно, что вы хотите в качестве вывода – HamZa

ответ

0
<?php 
    function parse($text) 
    { 
     // Find each character group: [...] 
     preg_match_all('/(.*?)(?:\[([^[\]]{1,30})\]|$)/s', $text, $matches, PREG_SET_ORDER); 
     $groups = []; 
     foreach ($matches as $match) { 
      if (!empty($match[1])) { 
       // Prefix: foo 
       $groups []= $match[1]; 
      } 
      if (!empty($match[2])) { 
       // Group: [a-z0-9] 
       // For each range, add the chars to an array. ['a', 'b', ..., 'z', '0', ..., '9'] 
       $chrs = []; 
       preg_match_all('/(.)(?:-(.))?/', $match[2], $ranges, PREG_SET_ORDER); 
       foreach ($ranges as $rng) 
       { 
        if (empty($rng[2])) { 
         $chrs []= $rng[1]; 
        } 
        else { 
         $chrs = array_merge($chrs, range($rng[1], $rng[2])); 
        } 
       } 
       $groups []= $chrs; 
      } 
     } 
     return $groups; 
    } 

    function permute($groups, $index = 0) 
    { 
     $result = []; 
     if ($index >= count($groups)) 
     { 
      // Reached the end. Return a single, empty result. 
      $result []= ''; 
     } 
     else if (is_string($groups[$index])) 
     { 
      // Current group is a simple string. Prepend it to all tail results. 
      $prefix = $groups[$index]; 
      foreach (permute($groups, $index+1) as $s) 
      { 
       $result []= $prefix . $s; 
      } 
     } 
     else { 
      // Otherwise it is an array of characters. Prepend each to every tail result. 
      $chars = $groups[$index]; 
      foreach (permute($groups, $index+1) as $s) 
      { 
       foreach ($chars as $ch) { 
        $result []= $ch . $s; 
       } 
      } 
     } 

     return $result; 
    } 

    $text = 'test[A-BXZ][0-1][x-z]foo'; 

    $groups = parse($text); 
    print_r($groups); 

    $permutations = permute($groups); 
    print_r($permutations); 
?> 

Выход:

Array 
(
    [0] => test 
    [1] => Array 
     (
      [0] => A 
      [1] => B 
      [2] => X 
      [3] => Z 
     ) 

    [2] => Array 
     (
      [0] => 0 
      [1] => 1 
     ) 

    [3] => Array 
     (
      [0] => x 
      [1] => y 
      [2] => z 
     ) 

    [4] => foo 
) 
Array 
(
    [0] => testA0xfoo 
    [1] => testB0xfoo 
    [2] => testX0xfoo 
    [3] => testZ0xfoo 
    [4] => testA1xfoo 
    [5] => testB1xfoo 
    [6] => testX1xfoo 
    [7] => testZ1xfoo 
    [8] => testA0yfoo 
    [9] => testB0yfoo 
    [10] => testX0yfoo 
    [11] => testZ0yfoo 
    [12] => testA1yfoo 
    [13] => testB1yfoo 
    [14] => testX1yfoo 
    [15] => testZ1yfoo 
    [16] => testA0zfoo 
    [17] => testB0zfoo 
    [18] => testX0zfoo 
    [19] => testZ0zfoo 
    [20] => testA1zfoo 
    [21] => testB1zfoo 
    [22] => testX1zfoo 
    [23] => testZ1zfoo 
) 

http://ideone.com/FxrLmC

permute функция также может быть записана в виде generator-function.

+0

он почти работает там, где несколько ошибок VERRY. Я сделал из него рабочий класс TNX verry much! –

+0

Какие ошибки? Он работал на ideone.com. –

Смежные вопросы