Slugify and Character Transliteration in C#(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 和字符转写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中的 Slugify 和字符转写
基础教程推荐
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
