Php url解析和编辑

时间:2015-11-13 09:15:22

标签: php http url

我搜索了“整个”stackoverflow但没有找到适合我的正确答案。我需要在php中更改url的主机。

  

此网址:http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126

     

致:http://example456.com/test?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126

我只需要更改域和路径或文件,到目前为止我已经有了这个:

$originalurl = http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400....
$parts = parse_url($originalurl);
$parts['host'] = $_SERVER['HTTP_HOST'];
$parts['path'] = '/test';
$modifiedurl = http_build_query($parts);
print_r(urldecode($modifiedurl));

但它回声

  

方案= HTTP&安培;主机=本地主机&安培;路径= /试验&安培;查询= T = DE&安培; P = 9372&安培; PL = bb02799a&安培;猫=安培; SZ = 400 ...

请不要使用某些strpos或类似的东西,因为我需要它是可变的。 谢谢;)

4 个答案:

答案 0 :(得分:1)

你必须手动连接一些。这有效:

$originalurl = "http://example123.com/query?t=de&p=9372";
$parts = parse_url($originalurl);
$new_path = '/test';
$modifiedurl = $parts['scheme'] . "://" . $_SERVER['HTTP_HOST'] . $new_path . (isset($parts['query']) ? "?".$parts['query']:"");
print_r($modifiedurl);

答案 1 :(得分:1)

$url = 'http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126';
$query = parse_url($url)['query'];

$newUrl = 'http://www.younewdomain.com/path?' . $query;

答案 2 :(得分:1)

采用了不同的方法:

$url = "http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126";
$new_host = "http://newhost.com/blab";

//explode at ? so you get the query
$split = explode("?",$url,2);

//build new url
$new_url = $new_host."?".$split[1];

//finish
echo $new_url;

答案 3 :(得分:0)

parse_url()的反向功能应该是http_build_url(),你试过吗?