【发布时间】:2016-02-21 20:38:35
【问题描述】:
我正在尝试将 Wordpress sanitize_file_name 函数从 PHP 转换为 C#,以便我可以使用它在我自己构建的网络应用程序上为我的网站文章生成 unicode slug。
这是我的课:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace MyProject.Helpers
{
public static class Slug
{
public static string SanitizeFileName(string filename)
{
string[] specialChars = { "?", "[", "]", "/", "\\", "=", "< ", "> ", ":", ";", ",", "'", "\"", "& ", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}" };
filename = MyStrReplace(filename, specialChars, "");
filename = Regex.Replace(filename, @"/[\s-]+/", "-");
filename.TrimEnd('-').TrimStart('-');
filename.TrimEnd('.').TrimStart('.');
filename.TrimEnd('_').TrimStart('_');
return filename;
}
private static string MyStrReplace(string strToCheck, string[] strToReplace, string newValue)
{
foreach (string s in strToReplace)
{
strToCheck = strToCheck.Replace(s, newValue);
}
return strToCheck;
}
// source: http://stackoverflow.com/questions/166855/c-sharp-preg-replace
public static string PregReplace(string input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (int i = 0; i < pattern.Length; i++)
{
input = Regex.Replace(input, pattern[i], replacements[i]);
}
return input;
}
}
}
我写了一个类似这样的标题:"let's say that I have --- in there what to do",但我得到了相同的结果,只有修剪了单个撇号(让我们 -> 让),没有其他任何改变。
我想要与 Wordpress 相同的等效转换。使用 ASP.NET 4.5 / C#
【问题讨论】:
-
不要在 C# 中使用正则表达式分隔符。从模式中删除
/。 -
@stribizhev 是的,我删除了它,它似乎工作。我将再次对其进行测试,以确保整个功能按预期工作。谢谢