繁体   English   中英

PHP获取没有查询字符串的URL-修改现有查询时

[英]PHP Get URL without Query String - While Modifiying existing query

长期潜伏在这里的第一次海报:

我搜索过高和低,并试图保持我的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. 保留Google自定义搜索查询字符串www.example.com/search.htm?q=term

  3. 保持其他几个搜索字符串接近GSE字符串示例

我已经看过一些示例,但是如果不作大量更改,没有一个对我有用,surley有一个更简单的方法。 提前致谢

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

正则表达式(Fiddle 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
  ?> 

您需要将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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM