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

Replaces all tokens in a given string with appropriate values.


$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


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


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);


rogical’s picture

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

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

tinny’s picture

// 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));
b8x’s picture

thank you

skobe’s picture


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:

$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, '=')
echo "Total number of submissions: $number_of_rows";

Can anybody help me with this?

sempepe’s picture

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) {

    \[             # [ - 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 :)

DamienMcKenna’s picture

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.

alexander_danilenko’s picture

osopolar’s picture

MHz’s picture

I'm confused as how to use callback, I want to replace .wav in my token output with .mp3 and assume I need to use call back to do this, so far I have:

token_replace('[commerce-product:commerce-file:file]', array('[commerce-product' => $commerce_product), array('callback' => 'function_to_remove_chars'));

I have read through the literature and searched through each of the 72 examples of token_replace here but am just not getting what I have to do.

mdolnik’s picture

 * Custom token_replace() callback function to convert new lines (\n) to <br> in resulting token replacement
 * Usage: $output_string = token_replace($input_string, array('node'=>$node), array('callback' => 'custom_function_convert_newlines_to_br'));
function custom_function_convert_newlines_to_br(&$token_results){
  foreach($token_results as $token => &$string) {
    $string = str_replace("\n",'<br>',$string);
$input_string = 'line one
line two
line three';

$output_string = token_replace($input_string, array('node'=>$node), array('callback' => 'custom_function_convert_newlines_to_br'));

//$output_string = 'line one<br>line two<br>line three';
jaylotta’s picture

It seems that the keys in the $data array must resolve to an entity type. For instance, a $data value that is a node type must be keyed as 'node'. Otherwise the following code in token_generate() will not function properly:

module_invoke_all('tokens', $type, $tokens, $data, $options);

This is a bad design design as it precludes multiple objects of the same type being used for token replace. I cannot for the life of me figure out how to have and 'node1' and 'node2' key if I want to do so.

joseph11’s picture

If you need to use token replacement for special user tokens (like [user:one-time-login-url], which is used in emails), additional parameters are necessary:

token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));

Code example is copied from core user module (file user.module).

tarasiadis’s picture

I use token_replace to get the order id from commerce check out and then to call views_embed_view to show a view with parameter the token_replace result.

My problem is that I could not transform the returned result of token_replace from string to integer. I try then below code:

$orderidtoken = token_replace('[commerce-order:order-number]');
print views_embed_view('order_data_email','page_1', $orderidtoken);

return the text ex. "234"

but when i try to convert the returned string to int I could not. Return everytime 0.
print (int)check_plain($ordernumbertoken);
print intval(check_plain($ordernumbertoken));
All the below return 0

Why? Is something I do wrong?


kenorb’s picture

Sample usage by replacing tokens for drupal_goto() paths:

 * Implements hook_drupal_goto_alter().
function mymodule_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  if (user_access('administer nodes') && strpos($path, '[') !== FALSE) {
    // If token is found in path, replace it.
    // This feature is only available for admins.
    // Example path: /some/path/[current-page:arg:4]/csv
    $path = token_replace($path);