文本 Slugify(URL)
将文本规范化为 URL 友好的 slug,支持小写、分隔符、自定义去停用词。
常见问题
Q: 中文字符会怎么处理?
A: 默认会移除音标后保留拼音字母。纯中文可能变为空,建议先手动转拼音后再 slugify,或使用中文拼音转换工具。
Q: 为什么我的结果是空的?
A: 可能输入全是标点/符号/空格,或启用停用词过滤后无剩余单词。尝试关闭停用词选项或调整输入内容。
Q: 分隔符应该用 - 还是 _?
A: SEO 推荐用 - (连字符),Google 会将其视为空格;_ (下划线) 会被视为连接符,不利于分词。文件名可任选。
Q: Slug 长度有限制吗?
A: 技术上无限制,但建议保持在 50 字符以内,便于 URL 显示与 SEO。过长的 slug 可能被搜索引擎截断。
如何通过编程语言生成 Slug?
JavaScript
function slugify(text) {
return text
.toLowerCase()
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^\w\s-]/g, "")
.trim()
.replace(/[\s_-]+/g, "-")
.replace(/^-+|-+$/g, "");
}
PHP
function slugify($text) {
$text = mb_strtolower($text);
$text = iconv("UTF-8", "ASCII//TRANSLIT", $text);
$text = preg_replace("/[^\w\s-]/", "", $text);
$text = preg_replace("/[\s_-]+/", "-", $text);
return trim($text, "-");
}
Python
import re
import unicodedata
def slugify(text):
text = text.lower()
text = unicodedata.normalize("NFKD", text)
text = text.encode("ascii", "ignore").decode("ascii")
text = re.sub(r"[^\w\s-]", "", text)
text = re.sub(r"[\s_-]+", "-", text)
return text.strip("-")
Go
import (
"regexp"
"strings"
"golang.org/x/text/unicode/norm"
)
func Slugify(text string) string {
text = strings.ToLower(text)
text = norm.NFKD.String(text)
re := regexp.MustCompile(`[^\w\s-]`)
text = re.ReplaceAllString(text, "")
re = regexp.MustCompile(`[\s_-]+`)
text = re.ReplaceAllString(text, "-")
return strings.Trim(text, "-")
}
Ruby
require "unicode"
def slugify(text)
text = text.downcase
text = Unicode.nfkd(text).gsub(/[^\x00-\x7F]/, "")
text = text.gsub(/[^\w\s-]/, "")
text = text.gsub(/[\s_-]+/, "-")
text.strip.gsub(/^-+|-+$/, "")
end
Java
import java.text.Normalizer;
public static String slugify(String text) {
text = text.toLowerCase();
text = Normalizer.normalize(text, Normalizer.Form.NFKD);
text = text.replaceAll("[^\\w\\s-]", "");
text = text.replaceAll("[\\s_-]+", "-");
return text.replaceAll("^-+|-+$", "");
}