创建SEO友好URI字符串的最佳方法

问题描述 投票:9回答:3

该方法应该只允许URI字符串中的“0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-”字符。

What is the best way to make nice SEO URI string?

java string char uri slug
3个回答
31
投票

这就是普遍的共识:

  1. Lowercase字符串。 string = string.toLowerCase();
  2. Normalize所有字符并摆脱所有diacritical marks(例如é,ö,à变成e,o,a)。 string = Normalizer.normalize(string, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
  3. Replace all-保留非字母数字字符,并在必要时崩溃。 string = string.replaceAll("[^\\p{Alnum}]+", "-");

总结如下:

public static String toPrettyURL(String string) {
    return Normalizer.normalize(string.toLowerCase(), Form.NFD)
        .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
        .replaceAll("[^\\p{Alnum}]+", "-");
}

3
投票

以下正则表达式将与您的算法完全相同。我不知道做这类事情的图书馆。

String s = input
.replaceAll(" ?- ?","-") // remove spaces around hyphens
.replaceAll("[ ']","-") // turn spaces and quotes into hyphens
.replaceAll("[^0-9a-zA-Z-]",""); // remove everything not in our allowed char set

1
投票

如果您想搜索更多信息,这些通常称为“slu”。

您可以查看其他答案,例如How can I create a SEO friendly dash-delimited url from a string?How to make Django slugify work properly with Unicode strings?

它们比javascript更多地涵盖了C#和Python,但是对于slug约定以及制作它们时可能遇到的问题(例如唯一性,unicode规范化问题等)有一些与语言无关的讨论。

© www.soinside.com 2019 - 2024. All rights reserved.