php中的组替换

时间:2015-01-09 17:55:29

标签: php regex

我需要以这种方式修改链接(全局)

http://www.domain.de/specific-folder/ {数据} /#链路

到此:

http://{data}.domain.de/#link

{data} = changing folder name

我试过了,但是我无法弄清楚如何在php(preg_replace)中处理组替换?

$re = "/\\/specific-folder\\/*([0-9,a-z,A-Z,-]*)(.*)/"; 
$str = "http://www.domain.de/specific-folder/data/#link"; 
$subst = $1 // works, but i can't get rid of the original search string (?)

非常感谢任何提示!

2 个答案:

答案 0 :(得分:0)

您可以使用:

$str = preg_replace('~(http://)www\.(domain\.de)/specific-folder/([^/]+)~', '$1$3$2', $str);

答案 1 :(得分:0)

^[^.]*\.([^\/]*)\/.*?\/({.*?})\/(#.*)$

试试这个。看看演示。

https://regex101.com/r/sH8aR8/44

$re = "/^[^.]*\\.([^\\/]*)\\/.*?\\/({.*?})\\/(#.*)$/m";
$str = "http://www.domain.de/specific-folder/{data}/#link";
$subst = "http://$2.$1/$3";

$result = preg_replace($re, $subst, $str);