function token_replace

You are here

7 token.inc token_replace($text, array $data = array(), array $options = array())

Replaces all tokens in a given string with appropriate values.

Parameters

$text: A string potentially containing replaceable tokens.

$data: (optional) An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.

$options: (optional) A keyed array of settings and flags to control the token replacement process. Supported options are:

  • language: A language object to be used when generating locale-sensitive tokens.
  • callback: A callback function that will be used to post-process the array of token replacements after they are generated. For example, a module using tokens in a text-only email might provide a callback to strip HTML entities from token values before they are inserted into the final text.
  • clear: A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated.
  • sanitize: A boolean flag indicating that tokens should be sanitized for display to a web browser. Defaults to TRUE. Developers who set this option to FALSE assume responsibility for running filter_xss(), check_plain() or other appropriate scrubbing functions before displaying data to users.

Return value

Text with tokens replaced.

18 calls to token_replace()
CommentTokenReplaceTestCase::testCommentTokenReplacement in modules/comment/comment.test
Creates a comment, then tests the tokens generated from it.
FileFieldPathTestCase::testUploadPath in modules/file/tests/file.test
Tests the normal formatter display on node display.
FileTokenReplaceTestCase::testFileTokenReplacement in modules/file/tests/file.test
Creates a file, then tests the tokens generated from it.
file_field_widget_uri in modules/file/file.field.inc
Determines the URI for a file field instance.
NodeTokenReplaceTestCase::testNodeTokenReplacement in modules/node/node.test
Creates a node, then tests the tokens generated from it.

... See full list

File

includes/token.inc, line 79
Drupal placeholder/token replacement system.

Code

function token_replace($text, array $data = array(), array $options = array()) {
  $text_tokens = token_scan($text);
  if (empty($text_tokens)) {
    return $text;
  }

  $replacements = array();
  foreach ($text_tokens as $type => $tokens) {
    $replacements += token_generate($type, $tokens, $data, $options);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }

  $tokens = array_keys($replacements);
  $values = array_values($replacements);

  return str_replace($tokens, $values, $text);
}

Comments

token_replace('[user:picture]', array('user' => $user)); works

token_replace('[user:picture:url]', array('user' => $user)); doesn't work

<?php
// print node id
print token_replace('[node:nid]', array('node' => $node));

// print author of node picture
print token_replace('[node:author:picture]', array('node' => $node));

// node created in time since creation
print token_replace('[node:created:since]', array('node' => $node));
?>

thank you

Hello,

i have a webform within a panel and want to read out the node-ID with PHP Code inside of a Markup field, to count submissions. But it seems that the php code is being executed before the Token is being converted. I'm using the %nid Token, because otherwise my script always takes the nid of the Panel-Page. Here is what i have:

<?php
$node
= menu_get_object(); // This returns...
$node_1 = $node->nid; //  ...the Panels nid
$node_2 = "%nid"; // this returns the desired nid but is not being converted
$node_3 = token_replace('%nid', array('node' => $node)); // this isn't either

$number_of_rows = db_select('webform_submissions')
->
condition('nid', $node_3, '=')
->
countQuery()
->
execute()
->
fetchField();
echo
"Total number of submissions: $number_of_rows";
?>

Can anybody help me with this?

I solved in this way because i didn't find any solution about it

/**
* Function to replace multiple several tokens
* using Drupal framework
*/
function _my_module_replace_multiple_tokens($token_text, $node) {

   preg_match_all('/
    \[             # [ - pattern start
    ([^\s\[\]:]*)  # match $type not containing whitespace : [ or ]
    :              # : - separator
    ([^\s\[\]]*)   # match $name not containing whitespace [ or ]
    \]             # ] - pattern end
    /x', $token_text, $matches);

  $final_text = $token_text;

  for ($i = 0; $i < count($matches[0]); $i++) {

    if ($matches[1][$i] == 'node') {
      $aux = $node;
    }

    $replacements[$matches[0][$i]] = token_replace($matches[0][$i], array($matches[1][$i] => $aux));
  }

  foreach ($replacements as $index_replace => $replace_value) {
    $final_text = str_replace($index_replace, $replace_value, $final_text);
  }

  return $final_text;
}

I'm sure it's possible to simplify this code, it's up to you :)

If the text format on the input object has the PHP filter enabled and the sanitize option is set to FALSE, the return string will include the unprocessed PHP code, which could be a security issue for any modules or custom code.