从给定的字符串索引集合中查找所有可能的排列(PHP)


Find all possible permutations from a given set for specific string indices (PHP)

我已经为此绞尽脑汁好几天了,我似乎被困住了。我是PHP新手,所以请原谅我的粗心和错误。

给定一个模式,例如电子邮件地址"ab@?b?"我是否需要替换'的任何实例?'a-e', '@'和'.'中的所有可能的排列

这是我现在的记录:

function permute($str, $ch, $i, $n, &$output) {
    if ($i == $n) {
        array_push($output, $str);
    } else {
        for ($x = $i; $x < $n; $x++) {
            for ($y = 0; $y < count($ch); $y++) {
                $str[$x] = $ch[$y];
                permute($str, $ch, $i + 1, $n, $output);
            }
        }
    }
}
# each ? in the pattern to be replaced by all possible permutations of characters in chars array
# a through e as well as @ and .
$output = array();
$chars = range('a', 'e');
array_push($chars, '@');
array_push($chars, '.');
# the pattern to be checked
$pattern = "ab@?b?.ca";
permute($pattern, $chars, 0, strlen($pattern), $output);

…这很接近我想要的,但不完全正确。该函数对字符串的每个字符进行操作,但它应该只对'?'进行操作。我还能做些什么我还没做的事吗?如果我弄明白了,我会在评论中回复并编辑!

这是我的工作解决方案:

function permute($str, $arr, $i, $n, &$result) {
    $nLen = strlen($n);
    // cycle through every position of needle
    while (($i = strpos($str, $n, $i)) !== false) {
        $i = $i + $nLen;
        // cycle through each replacement value
        foreach ($arr as $value) {
            $modified = substr_replace($str, $value, $i - $nLen, $nLen);
            // if there are no needles left, save it
            if (stristr($modified, $n) === false) {
                $result[] = $modified;
            }
            permute($modified, $arr, $i, $n, $result);
        }
    }
}
# each ? in the pattern to be replaced by all possible permutations of characters in chars array
# a through e as well as @ and .
$chars = range('a', 'e');
array_push($chars, '@');
array_push($chars, '.');
# the pattern to be checked
$pattern = "ab@?b?.ca";
$result = array();
$needle = '?';
$index = 0;
permute($pattern, $chars, $index, $needle, $result);
var_dump($result);

这假定您只想保存没有指针的值。例如,而不是:

array(63) {
  [0]=>
  string(9) "ab@ab?.ca"
  [1]=>
  string(9) "ab@aba.ca"
  [2]=>
  string(9) "ab@abb.ca"
  // etc...

输出:

array(49) {
  [0]=>
  string(9) "ab@aba.ca"
  [1]=>
  string(9) "ab@abb.ca"
  [2]=>
  string(9) "ab@abc.ca"
  // etc...

如果您确实想要第一个结果,那么只需删除stristr($modified, $n) === false条件。

无需写出算法,就可以完成相同的操作:

$var = "ab@?b?.co";
$var = str_replace("?","",$var);
print $var;
//ab@b.co