How do I fix a malformed URL in PHP? How do I fix a malformed URL in PHP? apache apache

How do I fix a malformed URL in PHP?


It's probably easier / better to replace or fix the client library, because it's not doing what it should (or it was designed for different specs).

But there is a regex which can help you.

/(.*?)(\/)?(\?.*)(\/.*)/

This matches the malformed strings in the examples and does not match the result strings. See a working demo at Rubular.

You can use it like this (though I am not sure if this is the best way to handle it, I would rather fix the output then trying to work with broken inputs):

$matches = array();$is_malformed = preg_match('/(.*?)(\/)?(\?.*)(\/.*)/', $_SERVER['REQUEST_URI'], $matches);if($is_malformed) {    $_SERVER['REQUEST_URI'] = $matches[1] . $matches[4] . $matches[2] . $matches[3];}


I approached the problem a little more generically in another question and with the help of @Yogesh Suthar came up with this as a working solution (improvements welcome):

$qs_match = array();$is_malformed = preg_match('$\?(.*?)\/$s', $_SERVER['REQUEST_URI'], $qs_match);if($is_malformed) {    $uri_parts = explode('?',$_SERVER['REQUEST_URI']); //break apart at the first query string param    //per https://stackoverflow.com/questions/4250794/simple-php-regex-question    $_SERVER['REQUEST_URI'] = $uri_parts[0].preg_replace('/^[^\/]*\//' , '/', $uri_parts[1]).'?'.$qs_match[1]; //recombined but modified part 2}