【发布时间】:2011-02-21 15:03:32
【问题描述】:
我有一个文本字符串,其中包含带有所有不同类型链接(相对、绝对、根相对)的 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" ... />
【问题讨论】:
-
必须是正则表达式吗?使用 DOM 类可以得到更准确的结果。
-
它必须是正则表达式,因为我无法保证 DOM 足够有效,任何基本的 DOM 阅读器都能正确解析。
标签: php regex hyperlink relative-path absolute-path