這是我工作的解決方案:
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 = "[email protected]?b?.ca";
$result = array();
$needle = '?';
$index = 0;
permute($pattern, $chars, $index, $needle, $result);
var_dump($result);
這是假設你只想要保存其中沒有針保持值。例如,而不是:
array(63) {
[0]=>
string(9) "[email protected]?.ca"
[1]=>
string(9) "[email protected]"
[2]=>
string(9) "[email protected]"
// etc...
這將輸出:
array(49) {
[0]=>
string(9) "[email protected]"
[1]=>
string(9) "[email protected]"
[2]=>
string(9) "[email protected]"
// etc...
如果你實際上想要做的第一個結果,然後簡單地去掉stristr($modified, $n) === false條件。