gpt4 book ai didi

c# - 将 Wordpress 清理文件名函数从 PHP 转换为 C#

转载 作者:行者123 更新时间:2023-11-30 17:40:50 24 4
gpt4 key购买 nike

我正在尝试将 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 -> lets),其他都没有改变。

我想要与 Wordpress 相同的等效转换。使用 ASP.NET 4.5/C#

最佳答案

因为在 C# 中没有 Action 修饰符,所以没有正则表达式分隔符。

解决方案是简单地从模式中删除 / 符号:

filename = Regex.Replace(filename, @"[\s-]+", "-");
^ ^

关于c# - 将 Wordpress 清理文件名函数从 PHP 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33808374/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com