【问题标题】:Converting Wordpress sanitize filename function from PHP to C#将 Wordpress 清理文件名函数从 PHP 转换为 C#
【发布时间】: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 是的,我删除了它,它似乎工作。我将再次对其进行测试,以确保整个功能按预期工作。谢谢

标签: c# asp.net .net regex


【解决方案1】:

由于在 C# 中没有动作修饰符,因此没有正则表达式分隔符。

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

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

【讨论】:

  • 效果很好。感谢您的快速回答。
  • 说是59秒,所以我去吃饭了:)我不会忘记的。再次感谢
猜你喜欢
  • 1970-01-01
  • 2015-01-17
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
相关资源
最近更新 更多