Sha*_*awn 17 language-agnostic string seo slug
拿一个如下的字符串:
在C#中:如何在逗号分隔的字符串列表中围绕字符串添加"引号"?
并将其转换为:
在-C-怎么办,我加引号围绕头字符串IN-A-逗号分隔的列表的串
要求:
ToSeoFriendly("hello world hello world", 14)return"hello-world"另请注意,是否应该有最小长度?
Sha*_*awn 10
这是我在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();
}
Run Code Online (Sandbox Code Playgroud)
我会按照以下步骤操作:
preg_replace()函数调用已经阻止了多个连字符,所以没有必要)所以,一起在函数(PHP)中:
function generateUrlSlug($string, $maxlen=0)
{
$string = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
if ($maxlen && strlen($string) > $maxlen) {
$string = substr($string, 0, $maxlen);
$pos = strrpos($string, '-');
if ($pos > 0) {
$string = substr($string, 0, $pos);
}
}
return $string;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9392 次 |
| 最近记录: |