doushuo1080 2018-09-19 00:08
浏览 66
已采纳

使用parse_url在php中无法更改get变量

I've looked at every post on SO that remotely pertains to this and I just can't figure this out. This code is taken directly from another SO post and was marked as the correct working answer:

$query = $_GET;
// replace parameter(s)
$query['d'] = 'new_value';
// rebuild url
$query_result = http_build_query($query);
// new link
<a href="<?php echo $_SERVER['PHP_SELF']; ?>?<?php echo $query_result; ?>">Link</a>

Again, taken straight from another post. When I try this code, i change the $_GET to the actual URL that i want to alter. When the code gets to the $query['d'] part, it tells me I get an illegal string offset and the error is the index that's specified. So then I parse the URL, and then do parse_str($query, $output) which in turn allows me to do $output['d'] and THEN I can set a new value to that variable. If I echo it out, it's fine.

But then I get to the http_build_query line, and it tells me that it's expecting an array or object and I can't build the new URL. Here is my code:

$link = parse_url('https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial', PHP_URL_QUERY);

 parse_str($link, $output);
 $output['oq'] = 'new value';

 $query_result = http_build_query($link);
echo $query_result;

This code yields that the http_build_query function wants an array or object...i guess i'm not giving it that in some way? What do I need to do to get this to work?

  • 写回答

1条回答 默认 最新

  • douxiaochun4964 2018-09-19 00:38
    关注

    If you want to rebuild the full URL after modifying the query parameters, you could do this:

    $url = 'https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial';
    $link = parse_url($url, PHP_URL_QUERY);
    parse_str($link, $output);
    $output['oq'] = 'new value';
    echo substr($url, 0, strpos($url, '?') + 1) . http_build_query($output);
    

    Output:

    https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=new+value
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效