C#中的Slugify和字符音译

Tra*_*v L 12 c# transliteration internationalization slug

我正在尝试将以下slugify方法从PHP转换为C#:http://snipplr.com/view/22741/slugify-a-string-in-php/

编辑:为方便起见,这里是上面的代码:

/**
 * Modifies a string to remove al non ASCII characters and spaces.
 */
static public function slugify($text)
{
    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

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

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

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

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

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

    return $text;
}
Run Code Online (Sandbox Code Playgroud)

除了我找不到以下PHP代码行的C#等价物之外,我没有遇到任何问题.

$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
Run Code Online (Sandbox Code Playgroud)

编辑: 目的是将非ASCII字符Reformáció Genfi Emlékm?ve El?tt转换为reformacio-genfi-emlekmuve-elott

Jon*_*röm 10

我还想补充一点,//TRANSLIT删除撇号,@ jxac解决方案没有解决这个问题.我不确定为什么,但首先将其编码为Cyrillic然后再编码为ASCII,您会得到类似的行为//TRANSLIT.

var str = "éåäöíØ";
var noApostrophes = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(str)); 

=> "eaaoiO"
Run Code Online (Sandbox Code Playgroud)

  • 我不确定你的实际音译是什么意思,但它肯定不会删除非重音字母.`ReformációGenfiEmlékműveElőtt`=>`Reformacio Genfi Emlekmuve Elott` (2认同)
  • 然而,"Привет"只是一个空字符串.这就是我说的,它删除了非重音的非拉丁字母.在您的示例中,它仅删除了重音符号,其余字母已经拉丁语,因此不会进行音译. (2认同)

iku*_*sin 9

在codeplex上有一个用于音译的.NET库 - unidecode.它通常使用从python移植的Unidecode表来实现.