PHP Replace and edit array elements from keywords -


i have following input:

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

i implement function replace $input elements $keywords elements, following output:

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

here point, function have replace $(+|-)[0-9]+ elements (like $+2, $-1, ...) $input element value (after has been replaced) , remove them. number row offset index :

  • $-1 = $+1 replaced $user = 'alexandre'
  • function_name($+2) replaced $-1 = $+1 (wich $user = 'alexandre')

so, final output be:

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

ok, after trying fix infinite recurtions, found :

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

maybe, find optimizations.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -