php 添加,更改或删除URL中的参数。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 添加,更改或删除URL中的参数。相关的知识,希望对你有一定的参考价值。

<?php
function change_url_param($params = null, $url = null) {
  if (!$url) { $url = '//' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; }
  $p = parse_url($url);
  if (isset($p['scheme'])) { $s = $p['scheme'] . '://'; } else { $s = '//'; }
  if (substr($url, 0, 2) == '//') { $s = '//'; }
  if (isset($p['host'])) { $h = $p['host']; } else { $h = ''; }
  if (isset($p['path'])) { $t = $p['path']; } else { $t = '/'; } 
  if (isset($p['query'])) { parse_str($p['query'], $q); } else { $q = array(); } 
  if (isset($p['fragment'])) { $f = '#' . $p['fragment']; } else { $f = ''; }
  if (gettype($params) === 'NULL') { $q = ''; }
  if (gettype($params) === 'string') { $params = array($params => null); }
  if (gettype($params) === 'array') { $q = http_build_query(array_filter(array_merge($q, $params), create_function('$a', 'return $a!==null;'))); }
  if ($q) { $q = '?' . $q; }
  $n = $s . $h . $t . $q . $f;
  return $n;
}

$url = 'http://example.com/?page=1&count=10&order=asc#top';

echo change_url_param(array(), $url) . "\n";
echo change_url_param(null, $url) . "\n";
echo change_url_param('count', $url) . "\n";
echo change_url_param(array('page'=>2), $url) . "\n";
echo change_url_param(array('order'=>null), $url) . "\n";
echo change_url_param(array('count'=>20), $url) . "\n";
echo change_url_param(array('view'=>'grid'), $url) . "\n";
echo change_url_param(array('count'=>50,'page'=>2,'view'=>'list'), $url) . "\n";

/* Output:
http://example.com/?page=1&count=10&order=asc#top
http://example.com/#top
http://example.com/?page=1&order=asc#top
http://example.com/?page=2&count=10&order=asc#top
http://example.com/?page=1&count=10#top
http://example.com/?page=1&count=20&order=asc#top
http://example.com/?page=1&count=10&order=asc&view=grid#top
http://example.com/?page=2&count=50&order=asc&view=list#top
*/
?>

以上是关于php 添加,更改或删除URL中的参数。的主要内容,如果未能解决你的问题,请参考以下文章

PHP 从URL中的查询字符串中删除所有参数,除了一个

如何导航到相同的URL但更改(或添加,如果错过)其中一个查询参数

使用 JavaScript 删除 URL 的参数 [重复]

如何从 WordPress 网站 URL 中删除 index.php [重复]

删除 GWT 中的 URL 参数

从 URL Laravel 5.3 中删除公共