Replace token

Drupal replace token

If you need replace a tokent to a value you can use the next code

<?php

// Load token.
$token = \Drupal::service('token');

// Or.
$token = \Drupal::token();

// Get site name from token.
$site_name = $token->replace('[site:name]');

Also, you can pass an argument to replace it

<?php

use Drupal\node\Entity\Node;

// Load token.
$token = \Drupal::service('token');

// Or.
$token = \Drupal::token();

// Load a node
$node = Node::load(123);

// Get site name from token.
$site_name = $token->replace('[node:title]', ['node' => $node]);

And one more note. If the replacement for this token doesn't exist the system will leave it as is. Just like plain text "[node:title]".

A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated.

<?php

// Load token.
$token = \Drupal::service('token');

// Or.
$token = \Drupal::token();

// Get site name from token.
$site_name = $token->replace('[site:name]', ['clear' => TRUE]);