1 options.element.inc | _form_options_from_text($text, $key_type, $flat = FALSE, &$duplicates = array()) |
Logic function for form_options_from_text(). Do not call directly.
See also
File
- core/
modules/ field/ modules/ options/ options.element.inc, line 285 - All logic for options form elements.
Code
function _form_options_from_text($text, $key_type, $flat = FALSE, &$duplicates = array()) {
$keys = array();
$items = array();
$rows = array_filter(explode("\n", trim($text)), 'strlen');
$group = FALSE;
foreach ($rows as $row) {
$row = trim($row);
$matches = array();
// Check for a simple empty row.
if (!strlen($row)) {
continue;
}
// Check if this row is a group.
elseif (!$flat && preg_match('/^\<((([^>|]*)\|)?([^>]*))\>$/', $row, $matches)) {
if ($matches[1] === '') {
$group = FALSE;
}
else {
$group = $matches[4] ? $matches[4] : '';
$keys[] = $group;
}
}
// Check if this row is a key|value pair.
elseif (($key_type == 'mixed' || $key_type == 'custom' || $key_type == 'numeric') && preg_match('/^([^|]+)\|(.*)$/', $row, $matches)) {
$key = $matches[1];
$value = $matches[2];
$keys[] = $key;
$items[] = array(
'key' => $key,
'value' => $value,
'group' => $group,
);
}
// Set this this row as a straight value.
else {
$items[] = array(
'key' => NULL,
'value' => $row,
'group' => $group,
);
}
}
// Expand the list into a nested array, assign keys and check duplicates.
$options = array();
$new_key = 1;
foreach ($items as $item) {
if (!is_numeric($item['key'])) {
continue;
}
$int_key = (int) $item['key'];
if (is_int($int_key)) {
$new_key = max($int_key, $new_key);
}
}
foreach ($items as $item) {
// Assign a key if needed.
if ($key_type == 'none') {
$item['key'] = $new_key++;
}
elseif (!isset($item['key'])) {
while (in_array($new_key, $keys)) {
$new_key++;
}
$keys[] = $new_key;
$item['key'] = $new_key;
}
if ($item['group']) {
if (isset($options[$item['group']][$item['key']])) {
$duplicates[] = $item['key'];
}
$options[$item['group']][$item['key']] = $item['value'];
}
else {
if (isset($options[$item['key']])) {
$duplicates[] = $item['key'];
}
$options[$item['key']] = $item['value'];
}
}
return $options;
}