Basically I am trying to do an str_replace with “?cat=(insert number here)”
$queryString2 = str_replace("cat=(insert number here)", "cat=4", $queryString);
Is there a way this can be accomplished? Str_replace + one character because the value im searching for could be anything.
?cat=7
?cat=3
?cat=4
Any suggestions?
A more reliable way of handling query strings would be to actually parse them.
The technique you originally describe is the job of a regular expression 🙂
The regular expression
cat=[0-9]+matches the stringcat=followed by one or more (+) digits ([0-9]).preg_replacereplaces 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=1withdog_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.