Question: I have a query string that may look like one of the following:

1. ?key=aa=bb
2. ?key=aa=bb=cc
3. ?key=aa=bb&key2=cc

etc.

What I want to do is replace the equal sign in the value part only. So it should result in this:

1. ?key=aa%3dbb
2. ?key=aa%3dbb%3dcc
3. ?key=aa%3dbb&key2=cc

I'm trying to do that with the following regex by using a look ahead. But it's not doing anything.

```
echo preg_replace("/=(?=[^&])=/", "%3d", 'http://www.example.com?key=aaa=bbb=ccc&key3=dddd');

```

[Example code here](http://codepad.viper-7.com/qEBjtJ)

How can I make this work?

Answer: 
You don't need regex, use the proper tools. `parse_url()` to get the query string (and whatever else you want), then `parse_str()` to get an array of the var/vals. Then `http_build_query()` will encode for you:

```
$query = parse_url('http://www.example.com?key=aaa=bbb=ccc&key3=dddd', PHP_URL_QUERY);
parse_str($query, $array);
$result = http_build_query($array);

```
What about this?

```
preg_replace_callback("/=([^&$]+)/", "myReplace", "http://www.example.com?key=aaa=bbb=ccc&key3=dddd");

function myReplace($matches) {
  return "=" . urlencode($matches[1]);
}

```