Pra*_*ant 1 c# regex seo function
我创建了一个函数,它将任何字符串转换为制表符分隔.
What's new in ASP.NET 4.0
Run Code Online (Sandbox Code Playgroud)
然后它将以上标题转换为以下:
what-s-new-in-asp-net-4-0
Run Code Online (Sandbox Code Playgroud)
我用它来制作我的URL的SEO.但我不确定它在所有情况下都能正常工作.到目前为止,我已经在我的数据库中的大约1000条记录上测试了这个函数,并且它适用于所有标题.Guyz请检查此功能并告诉我是否有可能失败此功能,如果此功能可能失败,请告诉我可以在我的应用程序中使用的正确功能.
public string SEO_makeTitle(object objTitle)
{
string strTitle = Convert.ToString(objTitle);
strTitle = Regex.Replace(strTitle.Trim(), @"\W", " "); //replace special chars
strTitle = Regex.Replace(strTitle.Trim(), @"\s{2,}", " "); //replace double space
strTitle = strTitle.Trim().Replace(" ", "-").ToLower();
return strTitle; //return - delimited title
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您可能想要考虑重音符号的样子.你正在替换"特殊"字符,但我怀疑这包括非ASCII字母.
我会首先尝试将重音字符转换为非重音字符.如果你知道诀窍,有一个相对简单的方法在C#中做到这一点:
static string RemoveAccents (string input)
{
string normalized = input.Normalize(NormalizationForm.FormKD);
Encoding removal = Encoding.GetEncoding
(Encoding.ASCII.CodePage,
new EncoderReplacementFallback(""),
new DecoderReplacementFallback(""));
byte[] bytes = removal.GetBytes(normalized);
return Encoding.ASCII.GetString(bytes);
}
Run Code Online (Sandbox Code Playgroud)
ToLower(CultureInfo.InvariantCulture)如果在土耳其运行代码,您可能还希望明确使用以避免问题.如果在运行之前运行ToLower ,这可能不会成为问题RemoveAccents.