C# 中的 Slugify 和字符转写

Slugify and Character Transliteration in C#(C# 中的 Slugify 和字符转写)
本文介绍了C# 中的 Slugify 和字符转写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to translate the following slugify method from PHP to C#: http://snipplr.com/view/22741/slugify-a-string-in-php/

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

For the sake of convenience, here the code from above:

/**
 * 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('~[^\pLd]+~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# 代码之外,其余部分的代码我没有遇到任何问题:

I got no probleming coding the rest except I can not find the C# equivalent of the following line of PHP code:

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

这样做的目的是将非 ASCII 字符,例如 Reformáció Genfi Emlékműve Előtt 翻译成 reformacio-genfi-emlekmuve-elott

推荐答案

我还想补充一点,//TRANSLIT 删除了撇号,而 @jxac 解决方案没有解决这个问题.我不知道为什么,但首先将其编码为西里尔字母,然后再编码为 ASCII,您会得到与 //TRANSLIT 类似的行为.

I would also like to add that the //TRANSLIT removes the apostrophes and that @jxac solution doesn't address that. I'm not sure why but by first encoding it to Cyrillic and then to ASCII you get a similar behavior as //TRANSLIT.

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

=> "eaaoiO"

这篇关于C# 中的 Slugify 和字符转写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)