PHP: Change URL parameter

ぐ巨炮叔叔 提交于 2020-01-05 08:01:14

问题


This is what I have

echo '<button><a href="'.$_SERVER['REQUEST_URI'].'&startrow='.($startrow+100).'">Next 100</a></button>';

I have 2 parameters in my url one is campaign, second is startrow, how can I just remove 'startrow' parameter and its value from the url. I want something like this.

echo '<button><a href="'.REMOVE &startrow=x($_SERVER['REQUEST_URI']).'&startrow='.($startrow+100).'">Next 100</a></button>';

When I press the next 100 button, the page reloads and it adds startrow parameter in the url hence if I pressed next 100 button 5 times, I have 5 startrow paramter in the url, so I want to remove the previous startrow parameter first then add the new one

My actual url: enquirytable.php/campaign=all&startrow=100

When I click on Next 100 button: enquirytable.php/campaign=all&startrow=100&startrow=200

What I want: enquirytable.php/campaign=all&startrow=200


回答1:


Probably the long way, but you can try this way. Here we are using parse_url and parse_str to achieve desired output.

Try with an example

<?php

$url="http://www.example.com/some/path?startrow=100&campaign=abc";
$parameter="startrow";
echo change_url_parameter($url,$parameter,200);

function change_url_parameter($url,$parameter,$parameterValue)
{
    $url=parse_url($url);
    parse_str($url["query"],$parameters);
    unset($parameters[$parameter]);
    $parameters[$parameter]=$parameterValue;
    return  $url["path"]."?".http_build_query($parameters);
}



回答2:


Building the URL that way is not clean, instead of having to remove some parameters, you should start from a clean route then add those needed.

You can do something like :

echo '<button><a href="'.$_SERVER['PHP_SELF'].'&startrow='.($startrow+100).'">Next 100</a></button>';

If you really want to do it with $_SERVER['REQUEST_URI'] this should work :

function getUrl($startRow) {
    $url = preg_replace('@&startnow=[\d]+@', '', $_SERVER['REQUEST_URI']);
    return $url.'&startrow='.$startRow;
}

// ...

echo '<button><a href="'.getUrl($startrow+100).'">Next 100</a></button>';


来源:https://stackoverflow.com/questions/47196081/php-change-url-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!