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

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

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

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


当前回答

我也遇到过类似的问题。我想拥有漂亮的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 "-";
    }
}

其他回答

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

我认为你正在寻找类似“URL编码”的东西——对URL进行编码,以便在网络上使用它是“安全的”:

这里有一个参考。如果你不想要任何特殊字符,只需删除任何需要URL编码的字符:

HTML URL编码参考

我发现当我通过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);

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

从SEO的角度来看,连字符比下划线更受欢迎。转换为小写,删除所有撇号,然后用一个连字符替换所有非字母数字字符字符串。修剪多余的连字符从开始和结束。