質問
どのように行って生成に優しいURLをクライアントまで、フルのC#?現在、私は簡単に置き換えスペースアンダースコアがどのようにうまく発生URLのようにスタックオーバーフロー?
例えば、どのように交換することはできま:
方法を優しいURLをクライアントまで、フルのC#?
入
か-ん-i-の生成-a-ワールドカップのメンバーにurl-イン-C
解決
べるものはいくつかありますが、こでジェフ-ソリューションです。
if (String.IsNullOrEmpty(title)) return "";
まぁのではない試みです。この機能が渡された空の文字列、もって真剣に違います。スローエラーやん反応します。
// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one
のです。ることを考慮し各操作を全く新しい文字列は、この悪い場合でも、性能というわけではありません。
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash
title = Regex.Replace(title, @"\-{2,}", "-");
再び、基本的には仕事:最初に、使用の正規表現に置き換え、複数の空間です。その後、正規表現を再度交換複数の文字です。二つの表現を構文解析、オートマトンを構築し、メモリに対して繰り返し処理を実行倍以上の文字列を二つの文字列:すべてのこれらの操作できるので、簡単にします。
の私の頭のな試験にもなり得るかということですが、同等の解
// make it all lower case
title = title.ToLower();
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
// replace spaces
title = title.Replace(' ', '-');
// collapse dashes
title = Regex.Replace(title, @"-{2,}", "-");
// trim excessive dashes at the beginning
title = title.TrimStart(new [] {'-'});
// if it's too long, clip it
if (title.Length > 80)
title = title.Substring(0, 79);
// remove trailing dashes
title = title.TrimEnd(new [] {'-'});
return title;
この手法を用いた文字列関数の代わりにregex機能char機能の代わりに文字列関数となりました。
他のヒント
こちらはどのようにします。がありますのでご注意くり端状態識を目..
if (String.IsNullOrEmpty(title)) return "";
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
// remove any leading or trailing spaces left over
title = title.Trim();
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash
title = Regex.Replace(title, @"\-{2,}", "-");
// make it all lower case
title = title.ToLower();
// if it's too long, clip it
if (title.Length > 80)
title = title.Substring(0, 79);
// remove trailing dash, if there is one
if (title.EndsWith("-"))
title = title.Substring(0, title.Length - 1);
return title;
これが、いようのないものを使用しwhitelistの有効な文字以内):
new Regex("[^a-zA-Z-_]").Replace(s, "-")
なしする文字列の末尾が"--".ぐそこまで来ているのかもしれま秒regexパンフレット、ホームページの先頭/末に文字列、およびその交換もので、内部で"--"を"-".
所属していません StackOverflow