I have an URL http://test.com/test?xyz=27373&page=4&test=5 which I want to tranform by replacing the page=4 through page=XYZ
how can I do that with preg_replace?
I have an URL http://test.com/test?xyz=27373&page=4&test=5 which I want to tranform by replacing the page=4 through page=XYZ
how can I do that with preg_replace?
Are wanting to replace each value with another, or replace both with one?
Yes, you can use
$url = preg_replace("/page=\d+/","page=XYZ",$oldurl="http://test.com/test?xyz=27373&page=4&test=5");
Or you can reconstruct the URL from $_GET
superglobal.
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
preg_match('/xyz=([^&]+)/', $url, $newpage);
$new = preg_replace('/page=([^&]+)/', $newpage[0], $url);
$new = preg_replace('/xyz=([^&]+)&/', '', $new);
This will turn
http://test.com/test?xyz=27373&page=4&test=5
into
http://test.com/test?page=27373&test=5
Forgive me if this isn't what you were looking to do, but your question isn't quite clear.
I'm sure you could do something with a regular expression. However, if the URL you've given is the one you're currently handling, you already have all the request variables in $_Request.
So, rebuild the URL, replacing the values you want to replace, and then redirect to the new URL.
Otherwise, go find a regexp tutorial.
If this is your own page (and you are currently on that page) those variables will appear in a global variable named $_GET
, and you could use something like array_slice
, unset
or array_filter
to remove the unwanted variables and regenerate the URL.
If you just have that URL as a string, then what exactly are the criteria for removing the information? Technically there's no difference between
...?xyz=27373&page=4&test=5
and
...?test=5&xyz=27373&page=4
so just removing all but the first parameter might not be what you want.
If you want to remove everything except the xyz
param. Take a look at parse_url
and parse_str
EDIT: There used to be informations here that were cleary wrong.
Do you want to set the value of xyz to the page value? I think you might need to specify a bit more. But this is easy to modify if you dont know regex.
$url = 'http://test.com/test?xyz=27373&page=4&test=5';
$urlQuery = parseUrl($url, PHP_URL_QUERY);
parse_str($urlQuery, $queryData);
$queryData['page'] = $queryData['xyz'];
unset($queryData['xyz']);
$query = http_build_query($queryData);
$outUrl = substr_replace($url, $query, strpos($url, '?'));