2

PHP 変数にあるサブドメインを照合してから$_SERVER['SERVER_NAME']、内部リダイレクトを実行したいと考えています。Apache または nginx の書き換えはオプションではありません。これは、クライアント/ユーザーに表示される外部の書き換えであるためです。

私の正規表現は(.*(?<!^.))subdomain\.example\.com、ご覧のとおり、サブドメイン (マルチレベル サブドメイン) 内のサブドメインに一致します。最初のキャプチャ グループは後で使用します。

これは私のPHPコードです:

if(preg_match('#(.*(?<!^.))subdomain\.example\.com#', $_SERVER['SERVER_NAME'], $match1)) {
    echo $match1[1] . 'anothersubdomain.example.com';
}

ただし、サブドメインがたとえばcsssubdomain.example.com、これは一致させたくない別のサブドメインであるため、これは失敗します。次の PHP スクリプトを使用して、一致をテストします。

$tests = array(
    '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 as $test => $correct_answer) {
        $result = preg_replace( '#(.*(?<!^.))subdomain\.example\.com#', '$1anothersubdomain.example.com', $test);
    echo 'Input:    ' . $test . "\n" . 
         'Expected: ' . $correct_answer . "\n" . 
         'Actual  : ' .$result . "\n";
    $passorfail =  (strcmp( $result, $correct_answer) === 0 ? "PASS\n\n" : "FAIL\n\n");
    echo $passorfail;
}

出力として得られます:

Input:    subdomain.example.com
Expected: anothersubdomain.example.com
Actual  : anothersubdomain.example.com
PASS

Input:    css.subdomain.example.com
Expected: css.anothersubdomain.example.com
Actual  : css.anothersubdomain.example.com
PASS

Input:    csssubdomain.example.com
Expected: csssubdomain.example.com
Actual  : cssanothersubdomain.example.com
FAIL

Input:    tsubdomain.example.com
Expected: tsubdomain.example.com
Actual  : tsubdomain.example.com
PASS

Input:    multi.sub.subdomain.example.com
Expected: multi.sub.anothersubdomain.example.com
Actual  : multi.sub.anothersubdomain.example.com
PASS

Input:    .subdomain.example.com
Expected: .subdomain.example.com
Actual  : .subdomain.example.com
PASS

奇妙なことは、一致するが一致csssubdomain.example.comしないことtsubdomain.example.comです。

この場合に使用できる正規表現を誰か知っていますか? 先読みと後読みのゼロ幅アサーションでいくつか試してみまし たが、実際には機能しませんでした。

4

1 に答える 1

1

このパターンを試すことができます:

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

これを許可する場合は、最初.toto.subdomain.example.comに追加するだけです\.?

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

ハイフン文字を許可したい場合は、文字クラスに追加するだけです:

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

部分文字列をハイフン文字で開始または終了することを許可しない場合:

~^((?:\.?\w+([\w-]*?\w)?\.)*?)subdomain\.example\.com~
于 2013-05-03T19:36:37.863 に答える