PHP替换和编辑关键字中的数组元素


PHP Replace and edit array elements from keywords

我有以下输入:

$input = [
    0 => '$id000001',
    1 => '$id000002',
    2 => '$id000003',
    3 => 'Alexandre'
];
$keywords = [
    '$id000001' => 'function_name($+2)',
    '$id000002' => '$user',
    '$id000003' => '$-1 = $+1'
];

我想实现一个函数,用$keywords元素替换$input元素,输出如下:

[
    0 => 'function_name($+2)',
    1 => '$user',
    2 => '$-1 = $+1',
    3 => 'Alexandre'
];

重点是,我的函数必须用$input元素值替换所有$(+|-)[0-9]+元素(如$+2$-1…)(在被替换后),然后删除它们。数字是行偏移索引:

  • $-1 = $+1将替换为$user = 'Alexandre'
  • function_name($+2)将替换为$-1 = $+1(即$user = 'Alexandre'

因此,最终输出将是:

[
    0 => function_name($user = 'Alexandre')
]

好的,在尝试修复无限递归之后,我发现了这个:

function translate($input, array $keywords, $index = 0, $next = true)
{
    if ((is_array($input) === true) &&
        (array_key_exists($index, $input) === true))
    {
        $input[$index] = translate($input[$index], $keywords);
        if (is_array($input[$index]) === true)
            $input = translate($input, $keywords, $index + 1);
        else
        {
            preg_match_all('/'$((?:'+|'-)[0-9]+)/i', $input[$index], $matches, PREG_SET_ORDER);
            foreach ($matches as $match)
            {
                $element = 'false';
                $offset = ($index + intval($match[1]));
                $input = translate($input, $keywords, $offset, false);
                if (array_key_exists($offset, $input) === true)
                {
                    $element = $input[$offset];
                    unset($input[$offset]);
                }
                $input[$index] = str_replace($match[0], $element, $input[$index]);
            }
            if (empty($matches) === false)
                $index--;
            if ($next === true)
                $input = translate(array_values($input), $keywords, $index + 1);
        }
    }
    else if (is_array($input) === false)
        $input = str_replace(array_keys($keywords), $keywords, $input);
    return $input;
}

也许,有人可以找到一些优化。