Dynamic form building - cleanest way to substitute tags with form elements? I have a string with tags, and form elements with elements corresponding to that tags:

$line = "This module contains [quantity] items of type [type]."
$elements = array(
  'quantity' =&gt; array (
    '#type' =&gt; 'textfield',
    //other settings
  ),
  'type' =&gt;  array (
    '#type' =&gt; 'select',
    //other settings
  ),
}


Now, I have:



I want to generate:



What's the most standard Drupal way to do this? Elements and string will be taken from database. I assume it should happen in hook_theme, but how to pass all values to it?
If the tags are not dynamic you can have an array of possible form elements and then just foreach over them with matches from a regex. Then just have your mymodule_form call a builder function that would look something like: 

&lt;?php
function my_dynamic_forms_dynamic_form($form, &amp;$form_state, $id) {
  $string = my_dynamic_forms_db_call_for_strings($id);

  $elements = my_dyanmic_forms_get_array_elements();

  $form = array();

  $reg = '/\[(.*?)\]/is';

  if($c = preg_match_all($reg, $string, $matches))
  {
    foreach($matches[1] as $match) {
      $form[$match] = $elements[$match];
    }
  }

  $form['actions']['submit'] = array(
    '#type' =&gt; 'submit',
    '#value' =&gt; 'Submit Form',
  );

  return $form;
}


function my_dyanmic_forms_get_array_elements() {
  $elements = array(
  'quantity' =&gt; array (
    '#type' =&gt; 'textfield',
    //other settings
  ),
  'type' =&gt;  array (
    '#type' =&gt; 'select',
    //other settings
  ));

  return $elements;
}

function my_dynamic_forms_db_call_for_strings($id) {
  $sql = 'SELECT string s from my_dynamic_form_strings_table s WHERE id = :id';

  $result = db_query($sql, array(':id', $id));

  return $result-&gt;fetchField();
}
?&gt;