代码之家  ›  专栏  ›  技术社区  ›  The Pixel Developer

网站地图编码的困境

  •  1
  • The Pixel Developer  · 技术社区  · 15 年前

    sitemap.org (实体转义)例如,它们有一个示例URL:

    http://www.example.com/ümlat.php&q=name
    

    http://www.example.com/%C3%BCmlat.php&q=name
    

    http%3A%2F%2Fwww.example.com%2F%C3%BCmlat.php%26q%3Dname
    

    我已经用上的这个函数解决了这个问题 PHP.net

    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', 
        '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%23', '%5B', '%5D');
    
    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+",
        "$", ",", "/", "?", "#", "[", "]");
    
    $string = str_replace($entities, $replacements, rawurlencode($string));
    

    在站点地图中使用URL的正确编码方式是什么?

    相关 RFC 3986

    1 回复  |  直到 15 年前
        1
  •  3
  •   Artefacto    15 年前

    问题是 http://www.example.com/ümlat.php&q=name 不是有效的url。

    (来源: RFC 1738 ,这是过时的,但在这里起作用,RFC3986确实允许更多的字符,但转义不需要转义的字符不会造成任何伤害)

    httpurl        = "http://" hostport [ "/" hpath [ "?" search ]]
    hpath          = hsegment *[ "/" hsegment ]
    hsegment       = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
    uchar          = unreserved | escape
    unreserved     = alpha | digit | safe | extra
    safe           = "$" | "-" | "_" | "." | "+"
    extra          = "!" | "*" | "'" | "(" | ")" | ","
    escape         = "%" hex hex
    search         = *[ uchar | ";" | ":" | "@" | "&" | "=" ]
    

    ;:@&=$-_.+!*'(), ,一个 0-9a-zA-Z 字符或转义序列(例如。 %A0 或者,等价地, %a0 ? 角色最多只能出现一次。这个 / 字符可以出现在路径部分,但不能出现在查询字符串中。编码其他字符的约定是计算它们的UTF-8表示并转义该序列。

    您的算法应该(假设主机部分不是问题……):

    • 提取路径部分
    • 提取查询字符串部分
    • 对于其中的每一个,查找无效字符
    • 用UTF-8编码这些字符
    • rawurlencode
    • 将URL中的字符替换为 rawurlencode编码