【问题标题】:PHP function: hyphen in URL's domain gonePHP函数:URL域中的连字符消失了
【发布时间】:2026-01-03 10:25:01
【问题描述】:

这个问题对于 PHP 知识不错的人来说应该不难,请你帮我解答一下。

这是从 URL 中删除所有过滤器(参数)的 PHP 函数(“清除过滤器”链接),但它也会从我的域中删除连字符,这是不受欢迎的行为。所以,当domain为“e-domain.com”时,返回“edomain.com”,最终过滤器清理URL不正确。我该如何解决? (如果您需要更多细节,请告诉我)谢谢!

<?php
                function _clear_filters_url($available_get = array('filter1','filter2','filter3')){
                    $_temp = parse_url('http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);

                    $_temp_root = $_temp['scheme'].'://'.$_temp['host'].$_temp['path'];
                    parse_str($_temp['query'], $_get_query);
                    $i = 0;
                    foreach($_get_query as $index => $item){
                        if(in_array($index, $available_get)){
                            if(!$i)$_temp_root.='?';
                            else $_temp_root.='&';
                            $_temp_root .= ($index.'='.$item);
                            $i++;
                        }
                    }
                    return($_temp_root);
                }
            ?>      


            <a href="<?php echo htmlspecialchars(_clear_filters_url()); ?>" id="mi-clear-top-filters"><?php echo $this->__('Clear filters'); ?></a>

【问题讨论】:

    标签: php url filter hyphen


    【解决方案1】:

    你不需要把它弄得这么复杂。所有 URL 变量都已放入 $_GET 或 $_REQUEST。

    function _clear_filters_url($available_get = array('filter1','filter2','filter3')){
        $filtered = array();
        foreach ($_GET as $index => $item) {
            if (in_array(index, $available_get)) {
                $filtered[] = urlencode($index).'='.urlencode($item);
            }
        }
        return 'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME'].'?'.implode(‘&’, $filtered);
    }
    

    【讨论】:

    • 感谢您的回复!我刚刚尝试过,现在我得到了几乎相同的结果,只是不考虑类别和 index.php:“edomain.com/index.php?”。在初始方式中,它返回“edomain.com/category/category-2”。嗯..我在 nginx 上,也许这可能是这里的原因
    • 执行 phpinfo() 并检查 $_SERVER 中的值。问题可能来自服务器设置,而不是您的脚本。
    • 谢谢!你是对的,_SERVER["SERVER_NAME"] 不正确。