regex-排除子域(Preg_Match)

2022-03-29 00:00:00 regex php preg-match

我想匹配一个域(带有preg_Match),但我想排除一个子域。

示例我要匹配example.org上除boon.example.org以外的所有子域:

我试过了:

$test = "boon.example.org";
$test2 = "null";
if(preg_match('#(?!boon)(w+.)?example.org#', $test, $output)) {
    $test2 = $output[2] .'example.org';
}
但是,test2的输出是: oon.example.org,而不是example.org

有人有答案吗?


解决方案

如果您只查找确切的子域,难道不能只检查字符串boon.example.org是否存在吗?对于这一点,使用正则表达式似乎有点过头了。

无论如何,以下正则表达式应该可以执行您想要的操作:

.*(?<!boon.|^.)example.org

将为boon.example.org以外的所有子域或boon.example.org的任何子域返回subdomain.example.org

相关文章