A more reliable way of handling query strings would be to actually parse them.
// If your original query string was just the data in $_GET, clone $_GET:
$new_query = $_GET;
// Otherwise, parse the original query string using parse_str:
parse_str($original_query_string, $new_query);
// Then, set the new cat value, and build a new query string.
$new_query['cat'] = 4;
$new_query_string = http_build_query($new_query);
The technique you originally describe is the job of a regular expression :)
$queryString2 = preg_replace('/cat=[0-9]+/', 'cat=4', $queryString);
The regular expression cat=[0-9]+
matches the string cat=
followed by one or more (+
) digits ([0-9]
). preg_replace
replaces all matches of the regular expression (argument 1) found in the original string (argument 3) with the replacement string (argument 2) and returns the result.
Note that this will also replace dog_and_cat=1
with dog_and_cat=4
. borkweb's answer is a more complex regex, but handles that edge case if it could arise (e.g. this is a query string provided by the user).
I prefer the actual query parsing, but the regular expression solution should ideally work just as well, assuming no edge cases.