In the beginning, I looked for the opportunity to post a regex in string and then make all possible combinations. So that hallo[A-B] would create halloA and halloB. but it seems that this is impossible (Regular expression listing all possibilities)
So now i am trying to create somthing that can handel:
[A-Z]
[a-z]
[0-9]
But i can not find anything usefull.
i have also found this (PHP dynamic creation of alphabet) but thats not what i am looking for to.
input:
test[A-B][0-1][x-z]
output:
testA0x
testA1x
testA0y
testA1y
testB0x
testB1x
testB0y
testB1y
My made class that worked for me:
<?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);
?>