我正在做一个有文章的网站,我需要文章有“友好”的url,基于标题。

例如,如果我的文章标题是“文章测试”,我希望URL是http://www.example.com/articles/article_test。

但是,文章标题(与任何字符串一样)可以包含多个特殊字符,这些字符不可能直接放在我的URL中。比如说,我知道?或#需要被替换,但我不知道所有其他。

url中允许使用哪些字符?什么东西是安全的?


当前回答

您需要注意两组字符:保留字符和不安全字符。

保留字符为:

&(“&”) 美元(美元) 加号(“+”) 逗号(,) 正斜杠("/") 冒号(“:”) 分号(“;”) = (" = ") 问号(“?”) “At”符号(“@”) 英镑(“#”)。

一般认为不安全的字符有:

空格(" ") 小于大于("<>") 左右括号("[]") 前后大括号("{}") 管(“|”) 反斜杠(\) 插入符号(“^”) 百分比(%)

我可能忘记了一个或多个,这导致我重复卡尔V的答案。从长远来看,您最好使用允许字符的“白名单”,然后对字符串进行编码,而不是试图与服务器和系统不允许的字符保持一致。

其他回答

我发现当我通过Ajax/PHP返回一个值到一个URL,然后由页面再次读取时,将我的URL编码为一个安全的URL非常有用。

PHP输出与URL编码器的特殊字符&:

// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";

// JavaScript sending the value to the URL
window.location.href = 'time.php?return=updated&val=' + msg;

// JavaScript/PHP executing the function printing the value of the URL,
// now with the text normally lost in space because of the reserved & character.

setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');", 360);

URI的格式在RFC 3986中定义。详见3.3节。

3-50个字符之间。可以包含小写字母、数字和特殊字符——点(.)、破折号(-)、下划线(_)和@。

我也遇到过类似的问题。我想拥有漂亮的url,并得出结论,我必须只允许字母,数字,-和_在url中。

这很好,但后来我写了一些漂亮的正则表达式,我意识到它识别所有UTF-8字符不是。net中的字母,这是搞砸了。对于. net正则表达式引擎来说,这似乎是一个众所周知的问题。所以我得到了这个解决方案:

private static string GetTitleForUrlDisplay(string title)
{
    if (!string.IsNullOrEmpty(title))
    {
        return Regex.Replace(Regex.Replace(title, @"[^A-Za-z0-9_-]", new MatchEvaluator(CharacterTester)).Replace(' ', '-').TrimStart('-').TrimEnd('-'), "[-]+", "-").ToLower();
    }
    return string.Empty;
}


/// <summary>
/// All characters that do not match the patter, will get to this method, i.e. useful for Unicode characters, because
/// .NET implementation of regex do not handle Unicode characters. So we use char.IsLetterOrDigit() which works nicely and we
/// return what we approve and return - for everything else.
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
private static string CharacterTester(Match m)
{
    string x = m.ToString();
    if (x.Length > 0 && char.IsLetterOrDigit(x[0]))
    {
        return x.ToLower();
    }
    else
    {
        return "-";
    }
}

unreserved = ALPHA / DIGIT / "-" / "."/ "_" / "~"