regex 替换在HTML页面文本中找到的url文件路径部分

fcipmucu  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(120)

给定一个html页面中的一些url,我想替换一些url如下:
示例url:https://example.com/cost-center/sub-one/article1从那一个我想替换文本之间的/cost-center/和最后一部分的网址(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/
所以基本上我想替换它的一些部分,同时保留最后一部分。
我尝试使用一个numerours正则表达式,例如:

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也没有好的结果。

t9aqgxwy

t9aqgxwy1#

从您对任务的描述和示例数据来看,URL是否/如何被引号 Package 实际上并不重要。您只需要匹配URL的前导部分以验证它是URL,然后隔离不需要的子字符串并替换它。
注意,我的替换值只有字符串test,没有对捕获组的引用。这是因为\K将忘记/释放所有匹配到该点的字符,而(?= ... )是一个前瞻,这意味着它不会消耗任何匹配的字符。
至于隔离模式中要替换的部分,我使用了一个包含正斜杠和空格的否定字符类,然后是一个字面正斜杠。这个子模式可以重复一次或多次(因为有+量词)。
代码:(Demo

echo preg_replace('#https://[^/]+/cost-center/\K([^/\s]+/)+(?=article)#', 'test/', $text);
8ljdwjyq

8ljdwjyq2#

我尝试了以下方法:正则表达式捕获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/。它将test/替换/const-center/和url最后一部分之间的文本
编辑:我修改了正则表达式,以便在URL位于HTML属性(如href)中的情况下包含引号和属性名称

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

相关问题