I was wondering which is the best way to turn a string (e.g. a post title) into a descriptive URL. the simplest way that comes to mind is by using a regex, such in:
public static Regex regex = new Regex(
"\\W+",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
string result = regex.Replace(InputText,"_");
which turns
"my first (yet not so bad) cupcake!! :) .//\."
into
my_first_yet_not_so_bad_cupcake_
then I can strip the last "_" and check it against my db and see if it's yet present. in that case I would add a trailing number to make it unique and recheck.
I could use it in, say
http://myblogsite.xom/posts/my_first_yet_not_so_bad_cupcake
but, is this way safe? should i check other things (like the length of the string) is there any other, better method you prefer? thanks
Here's what I do. regStripNonAlpha removes all the non-alpha or "-" characters. Trim() removes trailing and leading spaces (so we don't end up with dashes on either side). regSpaceToDash converts spaces (or runs of spaces) into a single dash. This has worked well for me.
static Regex regStripNonAlpha = new Regex(@"[^\w\s\-]+", RegexOptions.Compiled);
static Regex regSpaceToDash = new Regex(@"[\s]+", RegexOptions.Compiled);
public static string MakeUrlCompatible(string title)
{
return regSpaceToDash.Replace(
regStripNonAlpha.Replace(title, string.Empty).Trim(), "-");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With