2016-11-18 53 views
1

我一直在這裏擱置了我的大腦幾天,我似乎被卡住了。我是PHP新手,請原諒任何不合適或錯誤。查找給定集合中特定字符串索引(PHP)的所有可能的排列組合

給定一個模式,例如類似電子郵件地址「[email protected]?b?.ca」我需要替換'?'的任何實例。與來自一組字符'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 = "[email protected]?b?.ca"; 
permute($pattern, $chars, 0, strlen($pattern), $output); 

...這是非常接近我想要的,但不完全正確。該函數對字符串的每個字符進行操作,但它只應在'?'上進行。還有什麼我可以做的,我失蹤了?如果我想出來,我會在評論中回覆並編輯!

+1

預期結果是什麼? –

+0

以上例子:[email protected],[email protected],[email protected] ... [email protected],[email protected],[email protected] ...等等。 –

回答

0

這是我工作的解決方案:

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條件。

+0

這工程太棒了!謝謝! –

0

這做同樣的事情,而不必寫出來的算法:

$var = "[email protected]?b?.co"; 
$var = str_replace("?","",$var); 
print $var; 
//[email protected] 

希望這有助於。

+0

這根本不是一回事.. –

相關問題