如何根据字母变体数组获取所有类似的字符串

时间:2013-11-08 23:44:39

标签: php arrays

我一直试图将我的大脑包裹起来,但我正在有效地尝试根据一系列字母变体生成给定字符串的所有变体的数组/列表。

我有字符串“fabien”,每个字母都有一系列变体。例如A可以用4替换,i可以用1和l替换。因此,根据信息,我如何生成“fabien”的每个变体的列表。

$variants = array();
$variants['a'] = array('4');
$variants['i'] = array('1', 'l');

$string = 'fabien';

$result = getVariants('fabien', $variants);

print_r($results);

// Sample output:
Array ([0] => fabien [1] => f4bien [2] => fab1en [3] => fablen [4] => f4b1en [5] => f4blen)

2 个答案:

答案 0 :(得分:3)

您的案例可以通过递归轻松实现。那将是:

function getVariants($string, $variants)
{
    //here's about stripping 1 symbol from string's right, so 
    //may be you'll prefer to work with string functions:
    $string  = is_array($string)?$string:str_split($string);
    $symbol  = array_pop($string);
    $variant = array_key_exists($symbol, $variants)?
               array_merge([$symbol], $variants[$symbol]):
               [$symbol];
    $result  = [];
    if(!count($string))
    {
        return $variant;
    }
    foreach(getVariants($string, $variants) as $piece)
    {
        foreach($variant as $char)
        {
            $result[] = $piece.$char;
        }
    }
    return $result;
}

- 查看fiddle演示。这是怎么回事?答案是:长度为N的字符串的变化是它的右边符号'乘以'的变化,它的部分没有那个符号(即长度为N-1)。通过'乘法',我指的是两组的Decart乘积,然后是两部分的连接,即某一对。

答案 1 :(得分:1)

如果您不介意使用嵌套函数,请尝试以下方法:

function getVariants($string, $variants)
{
    // Store extra params for the recusion
    function _getVariants($string, $variants, $batch, $i, &$results)
    {
        if ($i >= strlen($string))
        {
            $results[] = $batch;
        }
        else
        {
            $character = $string[$i];

            // By default, just concat the current character
            _getVariants($string, $variants, $batch . $character, $i + 1, $results);

            if ( ! empty($variants[$character]))
            {
                // If there is something to replace
                foreach ($variants[$character] as $character)
                {
                    // Concat the replaced character
                    _getVariants($string, $variants, $batch . $character, $i + 1, $results);
                }
            }
        }
    }

    $results = array();
    _getVariants($string, $variants, '', 0, $results);
    return $results;
}

输出:

Array ( [0] => fabien [1] => fab1en [2] => fablen [3] => f4bien [4] => f4b1en [5] => f4blen )