3

I have part of a query string that I want to make a replacement in. I want to use preg_replace but am kind of hung up on the regex.

Can someone please help? What I need replaced are the GET vars.

Here is the string:

bikeType=G&nikeNumber=4351
3
  • They will be dynamically replaced. Commented Sep 23, 2010 at 10:39
  • Please can you clarify your question? You want the regex to match what exactly? Commented Sep 23, 2010 at 10:41
  • Can't you just access the get array to read the variables from there? Commented Sep 23, 2010 at 10:43

2 Answers 2

8

PHP has a convenient function to parse query strings: parse_str(). You might want to take a look at that or provide more details as your question isn't exactly clear.

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

1 Comment

And to reformat the array from parse_str, after modification, into a string you can use http_build_query.
4

You can use parse_str as was mentioned already.
In addition, if you want to put them back into a query string you can use http_build_query

Example:

parse_str('bikeType=G&nikeNumber=4351', $params);
$params['bikeType'] = 'F';
$params['nikeNumber'] = '1234';
echo http_build_query($params, '', '&'); 

Output

bikeType=F&nikeNumber=1234

Please note that you should not use parse_str without the second argument (or at least not with some consideration). When you leave it out, PHP will create variables from the query params in the current scope. That can lead to security issues. Malicious users could use it to overwrite other variables, e.g.

// somewhere in your code you assigned the current user's role
$role = $_SESSION['currentUser']['role'];
// later in the same scope you do
parse_str('bikeType=G&nikeNumber=4351&role=admin');
// somewhere later you check if the user is an admin
if($role === "admin") { /* trouble */ }

Another note: using the third param for http_build_query is recommended, because the proper encoding for an ampersand is &. Some validators will complain if you put just the & in there.

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.