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

时间:2010-05-19 22:17:00

标签: php regex hyperlink relative-path absolute-path

我有一个包含所有不同类型链接(相对,绝对,根相对)的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 个答案:

答案 0 :(得分:4)

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

<base href="/basepath/">

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

否则,如果您真的想使用正则表达式,请考虑您想要的相对路径必须是 path-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    = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="

所以URI的开头必须匹配:

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

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

答案 1 :(得分:0)

我想出了这个:

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

可能有点过于简单化了。我看到的明显缺陷是,当它在标签之外时它也会匹配href="something",但希望它能让你开始。

相关问题