PHP代码替换字符串中的特殊字符会删除这些字符


PHP Code to replace special characters in string removes the characters

此函数用于创建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;
}

不替换以下字符:

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

类似于:

lsctyztzyeiay

但相反,它完全去除了

所以这个字符串:

asdf 1234 3 ľščťlkiop

成为

asdf-1234-3-lkiop

而不是:

asdf-1234-3-lsctlkiop

你知道是什么导致了非英语字符的消失,以及如何使它们转换为英语变体吗?

我测试了您的函数,它似乎工作正常
你可以在这里用你的数据检查输出。