You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP验证含随机前缀子域名的URL?

解决PHP中带随机前缀子域名的URL校验问题

嘿,我来帮你搞定这个域名匹配的需求~原来的in_array()只能做精确匹配,没法直接支持通配符,所以我们得换个思路来实现“匹配127.0.0.1,同时匹配任意前缀结尾为develop.domain.com的子域名”的逻辑。

下面给你几种实用的解决方案:

方法1:使用字符串后缀匹配(PHP 8.0+推荐)

如果你的PHP版本在8.0及以上,直接用str_ends_with()函数检查域名后缀就好,代码简洁又高效:

$currentServerName = $_SERVER['SERVER_NAME'];

// 同时匹配三种情况:127.0.0.1、精确的develop.domain.com、任意前缀的xxx.develop.domain.com
if ($currentServerName === '127.0.0.1' 
    || $currentServerName === 'develop.domain.com'
    || str_ends_with($currentServerName, '.develop.domain.com')) {
    // 这里执行你的业务逻辑
    echo "域名匹配成功!";
}

方法2:兼容低版本PHP的后缀匹配

如果你的PHP版本低于8.0,可以用substr()手动判断后缀,兼容性拉满:

$currentServerName = $_SERVER['SERVER_NAME'];
$targetDomain = 'develop.domain.com';
$targetDomainLength = strlen($targetDomain);

$isMatched = false;
// 匹配精确的127.0.0.1
if ($currentServerName === '127.0.0.1') {
    $isMatched = true;
}
// 匹配精确的develop.domain.com
elseif ($currentServerName === $targetDomain) {
    $isMatched = true;
}
// 匹配带前缀的xxx.develop.domain.com
elseif (strlen($currentServerName) > $targetDomainLength + 1 
        && substr($currentServerName, -($targetDomainLength + 1)) === '.' . $targetDomain) {
    $isMatched = true;
}

if ($isMatched) {
    // 执行你的逻辑
    echo "域名匹配成功!";
}

方法3:使用正则表达式(灵活适配复杂规则)

如果之后需要更复杂的匹配规则,正则表达式会是更灵活的选择:

$currentServerName = $_SERVER['SERVER_NAME'];

// 正则规则:匹配127.0.0.1,或者任意合法前缀(包括空)的develop.domain.com
if (preg_match('/^(127\.0\.0\.1|([a-zA-Z0-9_-]+\.)?develop\.domain\.com)$/', $currentServerName)) {
    // 执行你的逻辑
    echo "域名匹配成功!";
}

这个正则的细节说明:

  • ^ 和 $ 确保匹配整个域名,避免出现部分匹配的错误
  • 127\.0\.0\.1 精确匹配本地IP
  • ([a-zA-Z0-9_-]+\.)? 表示可选的合法子域名前缀(允许字母、数字、下划线、连字符,后面跟一个点)
  • develop\.domain\.com 精准匹配目标主域名

内容的提问来源于stack exchange,提问作者ultraloveninja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:15:16