【发布时间】:2019-08-01 13:34:21
【问题描述】:
我需要将给定 html 文本中的几个给定相对 url 转换为绝对 url。
html 文本将与相对和绝对 url 混合,我需要结果 html 文本,它应该只包含具有以下规则的绝对 url。
- 原始 html 文本包含相对 URL 和绝对 URL 的混合
- 需要将
/test/1.html转换成https://www.example.com/test/1.html - 它应该忽略具有绝对 URL(.com 和 .de)的实例,例如
http://www.example.com/test/xxx.html,https://www.example.com/test/xxx.html,https://www.example.de/test/xxx.html,http://www.example.de/test/xxx.html
我知道使用preg_replace 的最佳方法是使用PHP,并尝试了以下代码。
$server_url = "https://www.example.com";
$html = preg_replace('@(?<!https://www\.example\.com)(?<!http://www\.example\.com)(?<!https://www\.example\.de)(?<!http://www\.example\.de)/test@iU', $server_url.'/test', $html);
但是,这并没有给出预期的结果,而是转换了所有 /test 链接,包括现有的绝对 URL。所以基本上有些网址最终会变成http://www.example.dehttp://www.example.com/test/xxx.html。
我不擅长regex,请帮我找到合适的regex 以获得想要的结果。
【问题讨论】:
-
是否所有的相关网址都以
/开头?或者它们也可以是 test/1.html 并且它们可以有查询字符串参数吗? -
为什么不能只检查 URL 是否以
http开头,如果不是,则与https://www.example.com连接? -
@Thefourthbird 它以
/开头
标签: php regex preg-replace