PHP add/modify a query string param & get the URL

2020-05-27 14:35发布

How can redirect the user back to the same page with the existing Query Strings but have 1 added/modified like "page".

I suppose 1 method is:

  1. parse the $_SERVER['QUERY_STRING'] into an array
  2. if page exists in the array, modify the value, else add it
  3. use http_build_query to get the query string to append to $_SERVER['PHP_SELF']

but is there a better/more direct way?

2条回答
虎瘦雄心在
2楼-- · 2020-05-27 15:14

Just to make sure you know about it, use parse_str to parse your query string:

<?php
parse_str($_SERVER['QUERY_STRING'], $query_string);
$query_string['page'] = basename($_SERVER['PHP_SELF']);
$rdr_str = http_build_query($query_string);
查看更多
放荡不羁爱自由
3楼-- · 2020-05-27 15:29

Using Jim Rubinstein's answer, I came up with a useful function that I thought I might share:

  function modQuery($add_to, $rem_from = array(), $clear_all = false){
  if ($clear_all){
     $query_string = array();
  }else{
     parse_str($_SERVER['QUERY_STRING'], $query_string);
  }
  if (!is_array($add_to)){ $add_to = array(); }
  $query_string = array_merge($query_string, $add_to);
  if (!is_array($rem_from)){ $rem_from = array($rem_from); }
  foreach($rem_from as $key){
     unset($query_string[$key]);
  }
  return http_build_query($query_string);
  }

For example: <a href="?<?=modQuery(array('kind'=>'feature'))?>">Feature</a>

查看更多
登录 后发表回答