使用纯bash创建URL友好的slug?

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

我正在采用一种纯粹的bash解决方案来“强化”变量,这并不像我的那样难看。

slugify:小写,缩短为63字节,除了0-9和a-z之外的所有内容都替换为 - 。没有领先/尾随 - 。结果是适合在URL主机名和域名中使用的字符串。输入很可能是一系列具有不良字符的单词,例如:

'Effrafax_mUKwT'uP7(Garkbit <\ 1} @NJ “RJ” Hactar * S; -H%×oLazlarl(= ZSS @ C9 qick:?BZarquonelW {X??>克@数k

其中一个slug看起来像:'effrafax-mukwt-up7-garkbit-1-njrjhactar-s-h-x-olazlarl-zss-c9-q'

slugify () {
  next=${1//+([^A-Za-z0-9])/-}
  next=${next:0:63}
  next=${next,,}
  next=${next#-}
  next=${next%-}
  echo $next
}

另外为什么${next//^-|-$}不会删除前缀和后缀'-'?其他建议?

bash slug parameter-expansion
1个回答
1
投票

我正在使用此功能,在我的bash配置文件中:

slugify () {
    echo "$1" | iconv -t ascii//TRANSLIT | sed -r s/[~\^]+//g | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | tr A-Z a-z
}

基于:https://gist.github.com/oneohthree/f528c7ae1e701ad990e6

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