[Drupal] How to Replace tokens in Drupal

| | 2 min read

This article explains how to replace tokens to webform, views, blocks and Drupal forms from the node body. The preg_replace function for replacing the tokens. The preg_replace function works in the same way as preg_match. preg_replace is used to search a regular expression and replace it.

preg_match_all is meant to collect all occurrences of a given pattern. Use the following codes to find your regex matches. If pattern exists, then returns matched tokens and it is available in $match[0], otherwise return null.


  $pattern = 'type your pattern here'; /*  /\\[([a-zA-z0-9_\-]+:[a-zA-z0-9_\-]+)+\\]/m    */
  $body_content = 'content here';
  $token = [type:form-id] // eg:  [webform:webform_node_id]
  preg_match_all($pattern, $body_content, $token);

preg_replace replaces all occurrences of the search pattern with the replacement string. After the replacement has occurred, the modified string would be returned; otherwise the string will remain unchanged. The first parameter specifies the pattern, the second parameter specifies the value to replace the value in find, and the third parameter specifies the string to search for.


  $matches = $match[0];
  foreach ($matches as $content_token) {
    $content_token_name = str_replace(array( '[', ']' ), '', $content_token);
    //breaks a $content_token_name into an array
    $type = explode(':', $content_token_name);
    // For view blocks, custom blocks, system blocks.
    // format [block:module_name:block_id].
    if ($type[0] == 'block') {
      $module_name = $type[1];
      $block_id = $type[2];
      $block = module_invoke($module_name, 'block_view', $block_id);
      $replacement = render($block['content']);
    }
    // For drupal web forms
    // Format [webform:webform_node_id]
    if ($type[0] == 'webform') {
      $node_id = $type[1];
      $node = node_load($node_id);
      $contact_form = drupal_get_form('webform_name_here_' . $node_id, $node);
      $replacement = drupal_render($contact_form);
    }
    // For drupal forms
    // Format [form:form_id]
    if ($type[0] == 'form') {
      $form_id = $type[1];
      $form_state = array();
      $form_state['build_info']['args'] = array();
      $form_state['build_info']['files']['menu'] = array();
      $form = drupal_build_form($form_id, $form_state);
      $replacement = render($form);
    }
    $body_content = preg_replace($content_token, $replacement, $body_content);
  }

If you have any doubts or queries while configuring, please get in touch with us.You may look into other solved issues related to Drupal tokens over here. We also offer drupal development offshore services. To know more contact us.