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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭