Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Wordpress sanitize filename function from PHP to C#

I'm trying to convert Wordpress sanitize_file_name function from PHP to C# so I can use it to generate unicode slugs for my site's articles on a web app that build myself.

This is my class:

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;
    }
 }
}

I put a title like: "let's say that I have --- in there what to do" but I get the same results only with the single apostrophe trimmed (let's -> lets), nothing else changed.

I want the same equivalent conversion as Wordpress'. Using ASP.NET 4.5 / C#

like image 475
Idan Shechter Avatar asked Feb 01 '26 12:02

Idan Shechter


1 Answers

Since in C# you do not have action modifiers, there are no regex delimiters.

The solution is simply to remove / symbols from the pattern:

filename = Regex.Replace(filename, @"[\s-]+", "-");
                                    ^      ^
like image 61
Wiktor Stribiżew Avatar answered Feb 04 '26 01:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!