<?php

# A broken URI like http://www.skyrock.com/1234/foo&bar.html
# will get rewritten as http://www.skyrock.com/1234/foo%26bar.html

function cb_clean_uri_path_component($prx) {
    $component = $prx[1];
    return '/' . rawurlencode($component);
}

function uri_clean($uri) {
    $matches = NULL;
    if (empty($uri)) {
        return $uri;
    }
    $ta = parse_url($uri);
    if (empty($ta)) {
        return $uri;
    }
    $scheme = $host = $path = $query = $fragment = '';
    if (!empty($ta['scheme'])) {
        $scheme = $ta['scheme'] . '://';
    }
    if (!empty($ta['host'])) {
        $host = $ta['host'];
    }
    if (!empty($ta['path'])) {
        $path = $ta['path'];
    }
    if (!empty($ta['query'])) {
        $query = '?' . $ta['query'];
    }
    if (!empty($ta['fragment'])) {
        $fragment = '#' . $ta['fragment'];
    }
    $fixed_path = preg_replace_callback('£/([^/?]+)£Dus',
                                        'cb_clean_uri_path_component', $path);
    $clean_uri = $scheme . $host . $fixed_path . $query . $fragment;
    
    return $clean_uri;
}

