You are here

public function TocFormatter::convertStringToId in TOC API 8

Convert a string to a valid HTML id.

Notes: At some point, D8 core or contrib (ie Drupal\pathauto\AliasCleaner) will provide a service to slugify strings based on predefined options.

Inspired by:

Parameters

string $text: String to be converted to a valid HTML id.

Return value

string A valid HTML id.

Overrides TocFormatterInterface::convertStringToId

File

src/TocFormatter.php, line 13

Class

TocFormatter
Defines a service for formatting a table of content's headers, numbering, and ids..

Namespace

Drupal\toc_api

Code

public function convertStringToId($text) {

  // Replace accents with their counterparts.
  $text = strtr($text, [
    'Š' => 'S',
    'š' => 's',
    'Đ' => 'Dj',
    'đ' => 'dj',
    'Ž' => 'Z',
    'ž' => 'z',
    'Č' => 'C',
    'č' => 'c',
    'Ć' => 'C',
    'ć' => 'c',
    'À' => 'A',
    'Á' => 'A',
    'Â' => 'A',
    'Ã' => 'A',
    'Ä' => 'A',
    'Å' => 'A',
    'Æ' => 'A',
    'Ç' => 'C',
    'È' => 'E',
    'É' => 'E',
    'Ê' => 'E',
    'Ë' => 'E',
    'Ì' => 'I',
    'Í' => 'I',
    'Î' => 'I',
    'Ï' => 'I',
    'Ñ' => 'N',
    'Ò' => 'O',
    'Ó' => 'O',
    'Ô' => 'O',
    'Õ' => 'O',
    'Ö' => 'O',
    'Ø' => 'O',
    'Ù' => 'U',
    'Ú' => 'U',
    'Û' => 'U',
    'Ü' => 'U',
    'Ý' => 'Y',
    'Þ' => 'B',
    'ß' => 'Ss',
    'à' => 'a',
    'á' => 'a',
    'â' => 'a',
    'ã' => 'a',
    'ä' => 'a',
    'å' => 'a',
    'æ' => 'a',
    'ç' => 'c',
    'è' => 'e',
    'é' => 'e',
    'ê' => 'e',
    'ë' => 'e',
    'ì' => 'i',
    'í' => 'i',
    'î' => 'i',
    'ï' => 'i',
    'ð' => 'o',
    'ñ' => 'n',
    'ò' => 'o',
    'ó' => 'o',
    'ô' => 'o',
    'õ' => 'o',
    'ö' => 'o',
    'ø' => 'o',
    'ù' => 'u',
    'ú' => 'u',
    'û' => 'u',
    'ý' => 'y',
    'þ' => 'b',
    'ÿ' => 'y',
    'Ŕ' => 'R',
    'ŕ' => 'r',
  ]);

  // Lowercase.
  $text = strtolower($text);

  // Remove apostrophes.
  $text = str_replace("'s ", ' ', $text);

  // Replace non letter or digits by -.
  $text = preg_replace('~[^\\pL\\d]+~u', '-', $text);

  // Remove number from beginning.
  // https://css-tricks.com/ids-cannot-start-with-a-number/
  $text = preg_replace('/^\\d+/', '-', $text);

  // Trim.
  $text = trim($text, '-');

  // Remove unwanted characters.
  $text = preg_replace('/[^-\\w]+/', '', $text);
  return $text;
}