【问题标题】:PHP Get URL without Query String - While Modifiying existing queryPHP获取没有查询字符串的URL-修改现有查询时
【发布时间】:2015-11-21 05:24:57
【问题描述】:

长期潜伏者第一次在这里发布海报:

我已经搜索过高和低,并试图保持我的 php 脚本与原来相同:

$url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

但是,当我回显 $url 时,我需要:

  1. www.example.com/?utm_source=etc中删除字符串 在多个文件名上删除 /? 之后的所有内容,例如 www.example.com/page.htm/?utm_source=etc www.example.com/page1.htm/?utm_source=etc 等等

  2. 保留谷歌自定义搜索查询字符串www.example.com/search.htm?q=term

  3. 保留几个其他搜索字符串关闭 GSE 字符串示例

我看过一些例子,但没有一个对我有用,除非做大量的改变,surley 有一个更简单的方法。 提前致谢

【问题讨论】:

标签: php string url replace echo


【解决方案1】:

这将为您完成这项工作。我使用了 php regex 和 preg_replace() 预定义函数。

正则表达式(小提琴Link

/www(\.)[A-Za-z0-9]+\.\w+(\/)(\?)?((\w)+(\.)(\w)+)?((.)+)?/i

php 示例

 <?php
    $input_line = 'www.example.com/?utm_source=etc'; //Input String
    $replace_String = ''; //specify your replace string here
    $regex = preg_replace("/www(\.)[A-Za-z0-9]+\.\w+(\/)(\?)?((\w)+(\.)(\w)+)?((.)+)?/i", $replace_String, $input_line);
    print_r($regex); //this will print the output with replaced string
  ?> 

【讨论】:

    【解决方案2】:

    您需要将 url 分成不同的部分,然后将它们全部重新组合在一起 - 这是唯一的方法。

    例如,如果您的网址是

        $url = www.example.com/page1.htm/?utm_source=etc&some_key=some_key_value&someothekey=someotherid
    
        $url_array = explode("?",$url);
    
        $url_path = $url_array[0];
        $url_params = explode("&",$url_array[1]);
        $i = 0;
        foreach($url_params as $url_param){ // Let's get specific url parameter and it's value
            $i++;
    
            $url_key = explode("=",$url_param)[0];
            $url_value = explode("=",$url_param)[1];
            $some_key = "some_key"; 
    
    /*
     * or use $i auto increment to find, relevant search parameter based on position e.g. 
     * if($i = 0){ // 0 is first etc.
     *    $some_key = $url_key;
     * }
     */
    
            // now that we have all keys - let's compare
            if($url_key === $some_key){
    
               $some_key_value .= $url_value; // Note the dot before ".=" so you can use it outside the loop, do the same if statements for any other keys you need 
            }     
    
    
        }
    
        $new_url = $url_path."?".$some_key."=".$some_key_value;
    

    【讨论】:

    • Jijo - 我的方法不是唯一的方法......但是使用 someold 和一些新参数重建字符串必须是某种超级胶水哈哈:v
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2020-04-06
    • 2011-03-12
    • 2021-04-16
    • 1970-01-01
    相关资源
    最近更新 更多