代码之家  ›  专栏  ›  技术社区  ›  Kendall Hopkins

Regex将相对链接替换为根相对链接

  •  1
  • Kendall Hopkins  · 技术社区  · 16 年前

    我有一个包含所有不同类型链接(相对、绝对、根相对)的html的文本字符串。我需要一个正则表达式,可以执行PHP的 preg_replace 将所有相对链接替换为根相对链接,而不接触任何其他链接。我已经有根路径了。

    替换的链接:

    <tag ... href="path/to_file.ext" ... >   --->   <tag ... href="/basepath/path/to_file.ext" ... >
    <tag ... href="path/to_file.ext" ... />   --->   <tag ... href="/basepath/path/to_file.ext" ... />
    

    未触及的链接:

    <tag ... href="/any/path" ... >
    <tag ... href="/any/path" ... />
    <tag ... href="protocol://domain.com/any/path" ... >
    <tag ... href="protocol://domain.com/any/path" ... />
    
    2 回复  |  直到 16 年前
        1
  •  4
  •   Gumbo    16 年前

    如果您只想更改基URI,可以尝试 BASE element :

    <base href="/basepath/">
    

    但是请注意,更改基URI会影响 全部的

    否则,如果您真的想要使用正则表达式,请考虑像您想要的相对路径必须是 路径noscheme (见 RFC 3986

    path-noscheme = segment-nz-nc *( "/" segment )
    segment       = *pchar
    segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
                    ; non-zero-length segment without any colon ":"
    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
    pct-encoded   = "%" HEXDIG HEXDIG
    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
                  / "*" / "+" / "," / ";" / "="
    

    ^([a-zA-Z0-9-._~!$&'()*+,;=@]|%[0-9a-fA-F]{2})+($|/)
    

    但是请使用一个合适的HTML解析器来解析HTML,并用它构建一个DOM。然后可以查询DOM以获得 href 属性并使用上面的正则表达式测试值。

        2
  •  0
  •   jdcantrell    16 年前

    preg_replace('#href=["\']([^/][^\':"]*)["\']#', $root_path.'$1', $html);
    

    可能有点太简单了。我看到的明显缺陷是它也会匹配 href="something"