Here is my solution in C#
private string ToSeoFriendly(string title, int maxLength) {
var match = Regex.Match(title.ToLower(), "[\w]+");
StringBuilder result = new StringBuilder("");
bool maxLengthHit = false;
while (match.Success && !maxLengthHit) {
if (result.Length + match.Value.Length <= maxLength) {
result.Append(match.Value + "-");
} else {
maxLengthHit = true;
// Handle a situation where there is only one word and it is greater than the max length.
if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
}
match = match.NextMatch();
}
// Remove trailing '-'
if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
return result.ToString();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…