1

I have an URL

http://example.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?

7 Answers 7

5

Yes, you can use

$oldurl = "http://test.com/test?xyz=27373&page=4&test=5"
$newurl = preg_replace("/page=\d+/", "page=XYZ", $oldurl);

Or you can reconstruct the URL from $_GET superglobal.

Sign up to request clarification or add additional context in comments.

Comments

2

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, '?'));

Comments

0
$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.

Comments

0

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.

Comments

0

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

Comments

-1

What exactly are you trying to do? The question is a little unclear.

$XYZ = $_GET['xyz']; $PAGE = $_GET['page'];

?

Comments

-1

Are wanting to replace each value with another, or replace both with one?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.