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

时间:2014-09-21 17:43:40

标签: php arrays replace nested

我有以下输入:

$input = [
    0 => '$id000001',
    1 => '$id000002',
    2 => '$id000003',
    3 => 'Alexandre'
];

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

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

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

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

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

因此,最终输出将是:

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

1 个答案:

答案 0 :(得分:0)

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

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;
}

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

相关问题