Php 匹配重定向的子域

Php 匹配重定向的子域,php,regex,redirect,preg-match,Php,Regex,Redirect,Preg Match,我想匹配PHP变量$\u SERVER['SERVER\u NAME']中的子域,然后执行内部重定向。Apache或nginx重写不是选项,因为这是客户端/用户可见的外部重写 我的正则表达式是(.*),如您所见,我在子域(多级子域)中匹配子域。我希望稍后使用的第一个捕获组 这是我的PHP代码: if(preg#u匹配('#)(.*? $tests=数组( 'subdomain.example.com'=>'anothersubdomain.example.com', 'css.subdomain

我想匹配PHP变量
$\u SERVER['SERVER\u NAME']
中的子域,然后执行内部重定向。Apache或nginx重写不是选项,因为这是客户端/用户可见的外部重写

我的正则表达式是
(.*),如您所见,我在子域(多级子域)中匹配子域。我希望稍后使用的第一个捕获组

这是我的PHP代码:

if(preg#u匹配('#)(.*?
$tests=数组(
'subdomain.example.com'=>'anothersubdomain.example.com',
'css.subdomain.example.com'=>'css.anothersubdomain.example.com',
'csssubdomain.example.com'=>'csssubdomain.example.com',
'tsubdomain.example.com'=>'tsubdomain.example.com',
'multi.sub.subdomain.example.com'=>'multi.sub.anothersubdomain.example.com',
'.subdomain.example.com'=>'.subdomain.example.com',
);
foreach($tests为$test=>$correct\u答案){
$result=preg_replace('#)(.*?
奇怪的是,它确实匹配
csssubdomain.example.com
,但不匹配
tsubdomain.example.com


有人知道这种情况下可以使用什么正则表达式吗?我尝试了一些方法,但没有真正起作用。

您可以尝试以下模式:

~^((?:\w+\.)*?)subdomain\.example\.com~
如果允许此
.toto.subdomain.example.com
,只需在开头添加
\.?

~^((?:\.?\w+\.)*?)subdomain\.example\.com~
如果要允许连字符,只需将其添加到字符类:

~^((?:\.?[\w-]+\.)*?)subdomain\.example\.com~
如果不允许子字符串以催眠字符开头或结尾:

~^((?:\.?\w+([\w-]*?\w)?\.)*?)subdomain\.example\.com~

谢谢,这工作得很好!只有一件事关于带有“连字符”(te-st.example.com)的子域呢?请参阅:
~^((?:\.?\w+([\w-]*?\w)?\.)*?)subdomain\.example\.com~