在HTML页面中给定一些URL,我想替换一些URL如下:

示例URL:https://example.com/cost-center/sub-one/article1 我想用另一个替换/cost-center/和url (article1)的最后一部分之间的文本用另一个文本(test)

这意味着上述URL将转换为:https://example.com/cost-center/test/article1

就我而言,在/cost-center/之后可能会有更多部分,并且URL可以以斜线结尾,也可以像以下示例中一样在内部引号:

https://example.com/cost-center/sub-one/sub-two/article-3/
https://example.com/cost-center/sub-one/sub-three/article-4
https://example.com/cost-center/sub-1/sub-two/sub-three/article-5/
'https://example.com/cost-center/sub-one/sub-two/article-3/'
'https://example.com/cost-center/sub-1/sub-two/sub-three/article-5'
"https://example.com/cost-center/sub-one/sub-three/article-4"
"https://example.com/cost-center/sub-1/sub-two/sub-three/article-5/"

这些将被替换如下:

https://example.com/cost-center/test/article-3/
https://example.com/cost-center/test/article-4
https://example.com/cost-center/test/article-5/
'https://example.com/cost-center/test/article-3/'
'https://example.com/cost-center/test/article-5'
"https://example.com/cost-center/test/article-4"
"https://example.com/cost-center/test/article-5/"

现在,假设URL在/cost-center/之后至少有一个和最多的三个部分;

例如https://example.com/cost-center/sub-1/sub-two/sub-three/article-5/

因此,基本上,我想在保留最后一部分时更换其中的某些部分。

我已经尝试使用数字等级,例如:

preg_replace('~https://example.com/cost-center/[^/]+/([^/]+)~', 'https://example.com/cost-center/test/$1', $url);

preg_replace('/(["\']?)(https:\/\/[^\/]+\/)([^\/]+)(\/[^"\s]*)?/', '$1$2test$4$1', $url);

我还尝试使用explode将URL分配,然后按零件手动解析,但事实证明非常复杂和丑陋。

ChatGPT也没有良好的结果。

分析解答

我尝试了以下内容: 正则捕获3组:

  1. URL的开始到/cost-center/
  2. /cost-center/与URL的最后一部分之间的一切
  3. URL的最后一部分可能以斜线而结束
$pattern = '/(https:\/\/example.com\/cost-center\/)(.*?)([^\/]+\/?$)/';
$replacement = '$1test/$3';
$result = preg_replace($pattern, $replacement, $url);

在替换字符串中,您将拳头和第三组($1 and $3)保留,然后用测试替换第二组。它将用test/替换/const-center/和URL的最后一部分之间的文本

编辑:我修改了以下等级以包括引号和HTML属性内部的情况(例如HREF)的情况的报价和属性名称

$pattern = '/(href=["\']https:\/\/example.com\/cost-center\/)(.*?)([^\/]+\/?["\'])/';