这是一个我编写的简单类,它使用了 parse_url。
我需要一种方法让页面保留 get 参数,同时也能编辑或添加它们。
我还有一些页面需要相同的 GET 参数,所以我添加了一种更改路径的方法。
<?php
class Paths{
private $url;
public function __construct($url){
$this->url = parse_url($url);
}
public function returnUrl(){
$return = $this->url['path'].'?'.$this->url['query'];
$return = (substr($return,-1) == "&")? substr($return,0,-1) : $return;
$this->resetQuery();
return $return;
}
public function changePath($path){
$this->url['path'] = $path;
}
public function editQuery($get,$value){
$parts = explode("&",$this->url['query']);
$return = "";
foreach($parts as $p){
$paramData = explode("=",$p);
if($paramData[0] == $get){
$paramData[1] = $value;
}
$return .= implode("=",$paramData).'&';
}
$this->url['query'] = $return;
}
public function addQuery($get,$value){
$part = $get."=".$value;
$and = ($this->url['query'] == "?") ? "" : "&";
$this->url['query'] .= $and.$part;
}
public function checkQuery($get){
$parts = explode("&",$this->url['query']);
foreach($parts as $p){
$paramData = explode("=",$p);
if($paramData[0] == $get)
return true;
}
return false;
}
public function buildQuery($get,$value){
if($this->checkQuery($get))
$this->editQuery($get,$value);
else
$this->addQuery($get,$value);
}
public function resetQuery(){
$this->url = parse_url($_SERVER['REQUEST_URI']);
}
}
?>
用法
Test.php?foo=1
<?php
$path = new Paths($_SERVER['REQUEST_URI']);
$path->changePath("/baz.php");
$path->buildQuery("foo",2);
$path->buildQuery("bar",3);
echo $path->returnUrl();
?>
返回:/baz.php?foo=2&bar=3
希望这对某些人有用!