1.20.x system.admin.inc system_transliterate_machine_name($string, $options)

Wrapper around transliteration_get() that handles common clean up on strings.

Parameters

string $string: The string to be transliterated.

$options: An array of options for further cleanup. This array includes:

  • langcode: The language code of the source string.
  • replace: The character with which to replace unknown characters in the string. Defaults to '_'.
  • replace_pattern: A pattern for replacing unknown characters with the "replace" value.
  • maxlength: The maximum allowed length of the returned string.

Return value

string: The transliterated and cleaned up string.

File

modules/system/system.admin.inc, line 2867
Admin page callbacks for the System module.

Code

function system_transliterate_machine_name($string, $options) {
  include_once BACKDROP_ROOT . '/core/includes/transliteration.inc';
  $defaults = array(
    'langcode' => $GLOBALS['language']->langcode,
    'replace' => '_',
    'replace_pattern' => NULL,
    'maxlength' => NULL,
  );
  $options = array_intersect_key($options, $defaults) + $defaults;

  // Build the default replacement pattern on the given "replace" property.
  if (!isset($options['replace_pattern'])) {
    $options['replace_pattern'] = '[^0-9A-Za-z' . $options['replace'] . ']+';
  }

  $replace = $options['replace'];
  $string = transliteration_get($string, $replace, $options['langcode']);

  // Remove remaining unsafe characters.
  if ($options['replace_pattern']) {
    $string = preg_replace('/' . $options['replace_pattern'] . '/', $options['replace'], $string);
  }
  // Replace whitespace.
  $string = str_replace(' ', $replace, $string);
  // Remove leading and trailing whitespace/unknown characters.
  $string = trim($string, $replace);
  // Collapse multiple consecutive replacement characters.
  $replace_regex = strlen($replace) ? "([$replace])[$replace]+|" : '';
  $string = preg_replace("/{$replace_regex}(_)_+|(\\.)\\.+|(-)-+/", '$1$2$3$4$5', $string);

  // Set maxlength.
  if ($options['maxlength']) {
    $string = substr($string, 0, $options['maxlength']);
  }

  return $string;
}