我需要将给定html文本中的几个给定的相对URL转换为绝对URL。
html文本将与相对URL和绝对URL混合在一起,我需要结果html文本,其中应仅包含具有以下规则的绝对URL。
/test/1.html
转换为https://www.example.com/test/1.html
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
以获得理想的结果。
答案 0 :(得分:1)
这应与 root 相对网址匹配:
^(\/[^\/]{1}.*\.html)$
您想要的网址将在$1
https://regex101.com/r/E1evez/2
<?php
$urls = [
'/test/1.html',
'http://www.example.com/test/xxx.html',
'https://www.example.de/test/xxx.html',
'/relative/path/file.html'
];
foreach( $urls as $url )
{
if( preg_match( '/^(\/[^\/]{1}.*\.html)$/', $url ) )
{
echo 'match: '.$url.PHP_EOL;
}
else
{
echo 'no match: '.$url.PHP_EOL;
}
}
输出:
match: /test/1.html
no match: http://www.example.com/test/xxx.html
no match: https://www.example.de/test/xxx.html
match: /relative/path/file.html
答案 1 :(得分:1)
如果所有网址都以正斜杠开头,则可以使用:
(?<!\S)(?:/[^/\s]+)+/\S+\.html\S*
说明
(?<!\S)
断言直接位于左侧的不是非空白字符(?:/[^/\s]+)+
重复匹配/
的1次以上,然后不重复/
或使用negated character class的空白字符/\S+
匹配/
并匹配1倍以上的非空格字符\.html\S*
与示例数据中的.html匹配,并且0倍以上是非空格字符如果您还想匹配/1.html
,则可以使用将量词更改为)*
而不是)+
要匹配比.html
多的扩展名,您可以指定允许匹配的内容,例如\.(?:html|jpg|png)
或使用字符类\.[\w-()]
并添加允许匹配的内容。