Files
ZelWiki/ZelWiki.Library/Navigation.cs
2025-02-20 15:20:28 +08:00

59 lines
1.6 KiB
C#

using System.Text;
using System.Text.RegularExpressions;
namespace ZelWiki.Library
{
public class Navigation
{
public static string Clean(string? str)
{
if (str == null)
{
return string.Empty;
}
//Fix names like "::Page" or "Namespace::".
str = str.Trim().Trim([':']).Trim();
if (str.Contains("::"))
{
throw new Exception("Navigation can not contain a namespace.");
}
// Decode common HTML entities
str = str.Replace(""", "\"")
.Replace("&", "&")
.Replace("&lt;", "<")
.Replace("&gt;", ">")
.Replace("&nbsp;", " ");
// Normalize backslashes to forward slashes
str = str.Replace('\\', '/');
// Replace special sequences
str = str.Replace("::", "_").Trim();
var sb = new StringBuilder();
foreach (char c in str)
{
if (char.IsWhiteSpace(c) || c == '.')
{
sb.Append('_');
}
else if (char.IsLetterOrDigit(c) || c == '_' || c == '/' || c == '-')
{
sb.Append(c);
}
}
string result = sb.ToString();
// Remove multiple consecutive underscores or slashes
result = Regex.Replace(result, @"[_]{2,}", "_");
result = Regex.Replace(result, @"[/]{2,}", "/");
return result.ToLower();
}
}
}