Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to remove GET variable with php

Tags:

string

php

i have this URI.

http://localhost/index.php?properties&status=av&page=1

i am fetching basename of the URI using following code.

$basename = basename($_SERVER['REQUEST_URI']);

the above code gives me following string.

index.php?properties&status=av&page=1

i would want to remove the last variable from the string i.e &page=1. please note the value for page will not always be 1. keeping this in mind i would want to trim the variable this way.

Trim from the last position of the string till the first delimiter i.e &

Update :

I would like to remove &page=1 from the string, no matter in which position it is on.

how do i do this?

like image 670
Ibrahim Azhar Armar Avatar asked Aug 25 '11 18:08

Ibrahim Azhar Armar


People also ask

What is unset () in PHP?

unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.

What is $_ GET in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>

Which function is used to delete variable?

The unset() function unsets a variable.

How do you empty a variable in PHP?

The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so. The unset() function has no return value.


2 Answers

Instead of hacking around with regular expression you should parse the string as an url (what it is)

$string = 'index.php?properties&status=av&page=1';

$parts = parse_url($string);

$queryParams = array();
parse_str($parts['query'], $queryParams);

Now just remove the parameter

unset($queryParams['page']);

and rebuild the url

$queryString = http_build_query($queryParams);
$url = $parts['path'] . '?' . $queryString;
like image 161
KingCrunch Avatar answered Sep 19 '22 10:09

KingCrunch


There are many roads that lead to Rome. I'd do it with a RegEx:

$myString = 'index.php?properties&status=av&page=1';
$myNewString = preg_replace("/\&[a-z0-9]+=[0-9]+$/i","",$myString);

if you only want the &page=1-type parameters, the last line would be

$myNewString = preg_replace("/\&page=[0-9]+/i","",$myString);

if you also want to get rid of the possibility that page is the only or first parameter:

$myNewString = preg_replace("/[\&]*page=[0-9]+/i","",$myString);
like image 45
ty812 Avatar answered Sep 18 '22 10:09

ty812