You are here

function _mathfield_extract_tokens in Math Field 7

Extract tokens from a mathfield expression.

Parameters

string $expression: The math expression that contains field tokens.

Return value

array An associative array of token data keyed by token.

4 calls to _mathfield_extract_tokens()
mathfield_get_tokens in ./mathfield.module
Get the element details for mathfield expression tokens.
mathfield_get_token_values in ./mathfield.module
Get the submitted values for token replacements.
mathfield_update_7000 in ./mathfield.install
Add field dependency setting for existing mathfields.
mathfield_validate_expression in ./mathfield.module
Element validate callback to populate the list of dependent fields.

File

./mathfield.module, line 506
Adds a dynamic math expression field.

Code

function _mathfield_extract_tokens($expression) {
  $tokens = array();

  // Match tokens with the following pattern: [$field_name:$delta:$column]
  // $field_name may only contain lowercase alphanumeric characters and
  // underscores. $delta is optional and will default to 0. $column is optional
  // and will be populated from the field settings if not provided.
  $pattern = '([a-z0-9_]+)';

  // Field name.
  $pattern .= '(:([0-9]+))?';

  // Delta.
  $pattern .= '(:([a-zA-Z0-9_]+))?';

  // Column.
  preg_match_all("/(\\[{$pattern}\\])/x", $expression, $matches);
  $search = $matches[1];

  // Full tokens including brackets.
  $fields = $matches[2];

  // Fields names.
  $deltas = $matches[4];

  // $matches[3] includes the ':'.
  $columns = $matches[6];

  // $matches[5] includes the ':'.
  for ($i = 0; $i < count($fields); $i++) {
    $delta = $deltas[$i];
    if (!is_numeric($delta) || $delta < 0) {
      $delta = 0;
    }
    $column = $columns[$i];
    if (empty($column)) {
      $field = field_info_field($fields[$i]);
      $keys = array_keys($field['columns']);
      $column = reset($keys);
    }
    $tokens[$search[$i]] = array(
      'field_name' => $fields[$i],
      'delta' => $delta,
      'column' => $column,
    );
  }
  return $tokens;
}