我创建了一个函数,它将任何字符串转换为制表符分隔符。

What's new in ASP.NET 4.0

然后它会将以上标题转换为以下内容:

what-s-new-in-asp-net-4-0

我用它来制作我的网址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
    }

由于

有帮助吗?

解决方案

您可能想要考虑一下口音会是什么样子。你正在取代“特殊”字符,但我怀疑这包括非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); 
 }

您可能还希望显式使用 ToLower(CultureInfo.InvariantCulture),以避免在土耳其运行代码时出现问题。如果在运行 RemoveAccents 之前运行ToLower ,这可能不会成为问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top