John Doeherskij
John Doeherskij

Reputation: 2587

PHP Code to replace special characters in string removes the characters

This function for creating URL slugs:

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

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

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

  // remove duplicate -
  $text = preg_replace('~-+~', '-', $text);

  // lowercase
  $text = strtolower($text);

  if (empty($text)) {
    return 'n-a';
  }

  return $text;
}

doesn't replace characters like:

ľščťýžťžýéíáý

to something like:

lsctyztzyeiay

but instead, it removes them completely

so this string:

asdf 1234 3 ľščťlkiop

becomes

asdf-1234-3-lkiop

instead of:

asdf-1234-3-lsctlkiop

Any idea what is causing the disappearance of non-English characters and how to make them convert to the English variant?

Upvotes: 0

Views: 1142

Answers (0)

Related Questions