正则表达式用根相对链接替换相对链接

2024-01-12

我有一串文本,其中包含具有所有不同类型链接(相对、绝对、根相对)的 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" ... />

如果您只想更改基本 URI,您可以尝试BASE element http://www.w3.org/TR/html4/struct/links.html#edef-BASE:

<base href="/basepath/">

但请注意,更改基本 URI 会影响all相对 URI 而不仅仅是相对 URI 路径。

否则,如果您确实想使用正则表达式,请考虑您想要的相对路径必须是以下类型路径方案 (see RFC 3986 https://www.rfc-editor.org/rfc/rfc3986):

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    = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

因此 URI 的开头必须匹配:

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

但是请使用适当的 HTML 解析器来解析 HTML 并从中构建 DOM。然后你可以查询 DOM 来获取href属性并使用上面的正则表达式测试值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

正则表达式用根相对链接替换相对链接 的相关文章

随机推荐