-2

everyone.

Is it possible to replace a specific GET variable value by using RegEx?

Here is what I have in mind.

I have a URL: https://example.com/category/?var1=value1&page=2&var2=value2

It can have different GET variables, but the one that it always has is "page".

What I want to do is this:

  1. Set the URL value to a string variable in PHP code - Done. $current_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  2. In that string replace the value of the "page" variable with another value but keep the rest of the URL the same so that I could use them for paging buttons - Struggling
  3. Take the string variable and echo it in a href tag - Done. <a href="<?php echo $current_link_next; ?>">Next</a>

The "page" value, of course, is not always 2 - it represents the page number where the user currently is so can be anything from 1 to any other integer.

I'm trying to do it with explodes and joins, but haven't succeeded yet. Maybe there is an easier way to replace values using RegEx?

3
  • Please show what you have tried. Do you want to do it as a rewrite/redirect, before page loads, or during page load? Commented Jun 19, 2022 at 11:57
  • Why not use $_GET for this? Commented Jun 19, 2022 at 12:02
  • I have edited my original question. Commented Jun 19, 2022 at 12:05

1 Answer 1

1

Here's a quick way to replace a parameter. Note, however, that this solution doesn't necessarily work out of the box for all URLs as some may not have a query.

# Your URL.
$url = "https://example.com/category/?var1=value1&page=2&var2=value2";

# Parse your URL to get its composing parts.
$parts = parse_url($url);

# Save the query of the URL.
$query = $parts["query"];

# Parse the query to get an array of the individual parameters.
parse_str($query, $params);

# Replace the value of the parametre you want.
$params["page"] = "your-value";

# Build the query.
$newQuery = http_build_query($params);

# Replace the old query with the new one.
$newUrl = str_replace($query, $newQuery, $url);

Snippet

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.