我正在尝试将Wordpress sanitize_file_name
函数从PHP转换为C#,这样我就可以在自己构建的web应用程序上使用它为我的网站文章生成unicode slugs。
这是我的班级:
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"
,但我得到了相同的结果,只是修剪了一个撇号(让我们->lets),其他什么都没有改变。
我想要与Wordpress相同的等效转换。使用ASP.NET 4.5/C#
由于在C#中没有操作修饰符,因此没有正则表达式分隔符。
解决方案是简单地从模式中删除/
符号:
filename = Regex.Replace(filename, @"[s-]+", "-");
^ ^