如何翻译"Lorem 3 ipsum dolor sit amet"?进入SEO友好的"Lorem-3-ipsum-dolor-sit-amet"在Java中? [英] How to translate "Lorem 3 ipsum dolor sit amet" into SEO friendly "Lorem-3-ipsum-dolor-sit-amet" in Java?

查看:129
本文介绍了如何翻译"Lorem 3 ipsum dolor sit amet"?进入SEO友好的"Lorem-3-ipsum-dolor-sit-amet"在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的博客应用中,用户可以输入任何文本作为其条目的标题,然后我根据该文本生成URL.

In my blog app, a user can enter any text as a title for their entry and then I generate a URL based on the text.

我验证其标题以确保其中仅包含字母和数字.

如果他们输入类似

Lorem 3 ipsum dolor sit amet

如何生成此文本的SEO友好版本:

how could I generate the more SEO friendly version of this text:

Lorem-3-ipsum-dolor-sit-amet

推荐答案

实际上,它并不像用连字符替换空格那样简单.您通常还希望将其全部改成小写,并规范化/替换变音符号,如á,ö,è等,它们都是无效 URL字符.唯一有效的字符被列为未保留的字符".在此Wikipedia页面的第二个表格中.

It's in practice really not as simple as replacing spaces by hypens. You would often also like to make it all lowercase and normalize/replace diacritics, like á, ö, è and so on which are invalid URL characters. The only valid characters are listed as "Unreserved characters" in the 2nd table of this Wikipedia page.

这种功能的外观如下:

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

它基本上执行以下操作:

It does basically the following:

  • 小写字符串
  • 删除合并的变音标记(在规范化工具将其从实际提取"出来之后)字符)
  • 用连字符替换非字母数字字符
  • lowercase the string
  • remove combining diacritical marks (after the Normalizer has "extracted" them from the actual chars)
  • replace non-alphanumeric characters by hyphens

这篇关于如何翻译"Lorem 3 ipsum dolor sit amet"?进入SEO友好的"Lorem-3-ipsum-dolor-sit-amet"在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆