In PHP, how to preserve 1st part of a link, keep 2nd and dynamically change the rest

不打扰是莪最后的温柔 提交于 2019-12-25 09:16:27

问题


Foe example. Lets take 4 URLs (existing or future) that follow the targeted pattern of:
https://KeepThisPartTill-cde.com/a/b/cde/ThisWillBeDifferent/ThisWillNot
https://KeepThisPartTill-cde.com/a/b/cde/ThisIsDifferent/ThisWillNot
https://KeepThisPartTill-cde.com/a/b/cde/ChangedAgain/ThisWillNot
https://KeepThisPartTill-cde.com/a/b/cde/AndAgain/ThisWillNot

So. If any of these (existing or future) links is clicked, we need them to be changed to:
https://KeepThisPartTill-cde.com/a/b/cde/WhateverThisWillBe/ThisWillNot?SomethingHere

This means:
If one clicks on a link that starts with https://KeepThisPartTill-cde.com/a/b/cde/, keep this part, add the part WhateverThisWillBe (which extends until you find the next /), add /ThisWillNot? (notice the ?) and finally add SomethingHere

Should I probably be using .htaccess

Please keep in mind that although it is about a WordPress site, I can figure the SomethingHere which is WordPress related but have a difficult time figuring out how to keep the first part intact when the second WhateverThisWillBe part is different (in every single link) and add /ThisWillNot? after it.


回答1:


Using preg_replace:

preg_replace('~(https://KeepThisPartTill-cde.com/a/b/cde/).+?(/ThisWillNot)~i',
             "$1WhateverThisWillBe$2?",
              $string);


来源:https://stackoverflow.com/questions/41205369/in-php-how-to-preserve-1st-part-of-a-link-keep-2nd-and-dynamically-change-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!