You are here

function _webform_select_options_from_text in Webform 7.4

Same name and namespace in other branches
  1. 6.3 components/select.inc \_webform_select_options_from_text()
  2. 7.3 components/select.inc \_webform_select_options_from_text()

Splits user values from new-line separated text into an array of options.

Parameters

string $text: Text to be converted into a select option array.

bool $flat: Optional. If specified, return the option array and exclude any optgroups.

Return value

array An array of options suitable for use as a #options property. Note that values are not filtered and may contain tokens. Individual values should be run through webform_replace_tokens() if displaying to an end-user.

10 calls to _webform_select_options_from_text()
_webform_analysis_component in ./webform.api.php
Calculate and returns statistics about results for this component.
_webform_analysis_grid in components/grid.inc
Implements _webform_analysis_component().
_webform_csv_data_grid in components/grid.inc
Implements _webform_csv_data_component().
_webform_csv_headers_grid in components/grid.inc
Implements _webform_csv_headers_component().
_webform_display_grid in components/grid.inc
Implements _webform_display_component().

... See full list

File

components/select.inc, line 1011
Webform module multiple select component.

Code

function _webform_select_options_from_text($text, $flat = FALSE) {
  static $option_cache = array();

  // Keep each processed option block in an array indexed by the MD5 hash of
  // the option text and the value of the $flat variable.
  $md5 = md5($text);

  // Check if this option block has been previously processed.
  if (!isset($option_cache[$flat][$md5])) {
    $options = array();
    $rows = array_filter(explode("\n", trim($text)));
    $group = NULL;
    foreach ($rows as $option) {
      $option = trim($option);

      /*
       * If the Key of the option is within < >, treat as an optgroup
       *
       * <Group 1>
       *   creates an optgroup with the label "Group 1"
       *
       * <>
       *   Unsets the current group, allowing items to be inserted at the root element.
       */
      if (preg_match('/^\\<([^>]*)\\>$/', $option, $matches)) {
        if (empty($matches[1])) {
          unset($group);
        }
        elseif (!$flat) {
          $group = $matches[1];
        }
      }
      elseif (preg_match('/^([^|]+)\\|(.*)$/', $option, $matches)) {
        $key = $matches[1];
        $value = $matches[2];
        isset($group) ? $options[$group][$key] = $value : ($options[$key] = $value);
      }
      else {
        isset($group) ? $options[$group][$option] = $option : ($options[$option] = $option);
      }
    }
    $option_cache[$flat][$md5] = $options;
  }

  // Return our options from the option_cache array.
  return $option_cache[$flat][$md5];
}