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

问题描述

我试图从翻译到PHP C#以下slugify方法:
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/

修改为了方便起见,这里从上面的code:

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('~[^\\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;
}

我没有probleming编码其余的除了我无法找到C#等值以下行PHP code的:

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óGenfiEmlékműveElőtt reformacio-genfi​​-emlekmuve-elott

推荐答案

我也想补充一点, // TRANSLIT 删除撇号和@jxac解决方案没有按T解决这个问题。我不知道为什么,但首先它编码到西里尔文,然后以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"

这篇关于Slugify和字符音译在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:43