There are several ways to solve this problem. These are the two most prominent way to achieve this.
1. Php way: Parse, trim and rebuild
2. Using preg_replce
First one is the easy way to do it and also do not require any external library.
On the other hand, the second one is bit lengthy but clean way to achieve it and also require an external library (pecl/http) to rebuild the URL which has been disassembled by parsing it.