一开始,我寻找机会在字符串中发布一个正则表达式,然后进行所有可能的组合。因此,hallo[AB] 将创建 halloA 和 halloB。但这似乎是不可能的(正则表达式列出了所有可能性)
所以现在我正在尝试创建可以处理的东西:
[A-Z]
[a-z]
[0-9]
但我找不到任何有用的东西。
我也发现了这个(PHP 动态创建字母表),但这不是我想要的。
输入:
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);
?>