C#中的Slugify和字符音译

我正在尝试将以下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; } 

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

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

编辑:目的是将非ASCII字符,例如Reformáció Genfi Emlékműve Előttreformacio-genfi-emlekmuve-elott

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

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

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

转换为字符串:

 byte[] unicodeBytes = Encoding.Unicode.GetBytes(str); byte[] asciiBytes = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, unicodeBytes); string asciiString = Encoding.ASCII.GetString(asciiBytes); 

转换为字节:

 byte[] ascii = Encoding.ASCII.GetBytes(str); 

@Thomas Levesque是对的,将被输出流编码…

要删除变音符号(重音符号),可以使用String.Normalize函数,如下所示:

http://www.siao2.com/2007/05/14/2629747.aspx

这应该照顾大多数情况(字形真的是一个字符加上一个重音标记)。 对于一个更具侵略性的字符匹配(用于处理像斯堪的纳维亚人削减的o [Ø],有向图和其他异形字形的情况),有表格方法:

http://www.codeproject.com/KB/cs/UnicodeNormalization.aspx

除了规范化之外,这还包括大约1,000个符号映射。

(注意,在您的示例中,正则表达式替换删除了所有标点符号)