https://url.spec.whatwg.org/#example-url-parsing
354041
final static function normalize(string $url):string{#{{{

    if(isset(
      $_SERVER['REQUEST_SCHEME'],
      $_SERVER['REQUEST_HOST'],
      $_SERVER['REQUEST_PORT'],
      $_SERVER['REQUEST_URI'],
      $_SERVER['SERVER_PORT']
    ) || PHP_SAPI ==='cli')
      return $url;

    $arr = parse_url($url);
    if($arr===false) return '';

    $a = [
      $arr['scheme']??$_SERVER['REQUEST_SCHEME'],
      '://',
      $arr['user']??'',
      ':',
      $arr['pass']??'',
      '@',
      $arr['host']??$_SERVER['HTTP_HOST'],
      ':',
      $arr['port']??$_SERVER['SERVER_PORT'],
      substr($_SERVER['REQUEST_URI'],0, strrpos($_SERVER['REQUEST_URI'],'/')+1),
      $arr['path']??'',
      '?',
      $arr['query']??'',
      '#',
      $arr['fragment']??'',
    ];

    if(!in_array($a[0], ['http','https'])) return '';

    if($a[12]==='')            unset($a[11],$a[12]);
    if($a[14]==='')            unset($a[13],$a[14]);
    if($a[8]==80)              unset($a[7],$a[8]);
    if($a[4]==='')             unset($a[3],$a[4]);
    if($a[2]==='')             unset($a[2],$a[3],$a[4],$a[5]);
    if(strpos($a[10],'/')===0) unset($a[9]);

    while(strpos($a[10],'../')===0){
      $a[10] = substr($a[10],3);
      $a[9] = dirname($a[9]);
      if($a[9]!=='/') $a[9] .= '/';
    }

    while(strpos($a[10],'./')===0){
      $a[10] = substr($a[10],2);
    }

    if($a[10]==='.') unset($a[10]);

    return implode($a);
  }
21012
def domain_parse(url):
    
    url = url.lower()
    if not url.startswith('http://') and not url.startswith('https://'):
        url = '{schema}{host}'.format(schema='http://', host=url)
    url = urlparse(url)
    if not url.hostname:
        raise ValueError('Invalid domain provided')

    # Strip www prefix any additional URL data
    url = urlparse('{scheme}://{host}'.format(scheme=url.scheme, host=url.hostname.lstrip('www.')))
    return url
1153110
def parse_url(request, url):
    """"""
    try:
        validate = URLValidator()
        validate(url)
    except ValidationError:
        if url.startswith('/'):
            host = request.get_host()
            scheme = 'https' if request.is_secure() else 'http'
            url = '{scheme}://{host}{uri}'.format(scheme=scheme,
                                                  host=host,
                                                  uri=url)
        else:
            url = request.build_absolute_uri(reverse(url))
    return url
882791
function parseUrl (url) {
  const regex = /(https?).*\/(.+)\/thread\/(\d+)/g
  let protocol
  let board
  let threadNo

  try {
    [, protocol, board, threadNo] = regex.exec(url)
  } catch (err) {
    throw new Error('Invalid 4chan URL!')
  }

  return {
    protocol,
    board,
    threadNo: Number.parseInt(threadNo)
  }
}
369134
function parseURL(url) {
  let urlLike;

  if (typeof URL === 'function') {
    urlLike = new URL(url);
  } else {
    urlLike = document.createElement('a');
    urlLike.setAttribute('href', url);
  }

  const { hostname, pathname, search } = urlLike;

  return { hostname, pathname, search };
}
1177432
def try_parse_url(url):
    
    if len(url.strip()) < 4:
        logger.info('URL too short: {}'.format(url))
        return None
    try:
        parsed_url = urlparse(url)
    except ValueError:
        logger.info('Parse URL ValueError: {}'.format(url))
        return None
    if parsed_url.scheme:
        return parsed_url
    try:
        parsed_url = urlparse('http://' + parsed_url.geturl())
    except ValueError:
        logger.info('Invalid URL for assumed http scheme: urlparse("{}") from "{}" '.format('http://' + parsed_url.geturl(), url))
        return None
    if not parsed_url.scheme:
        logger.info('Unable to guess a scheme for URL: {}'.format(url))
        return None
    return parsed_url
860481
function RouteRule_parseRequest(method, url) {

        var matches,
            route,
            key,
            result = [],
            escape = [],
            params = {},
            current;
        //match pathname
        matches = this.match(this.pattern, this.trim(url.pathname, '/'));


        if (!matches.length || !this.checkMethod(method)) {
            return false;
        }
        params = url.query;


        for (key in params) {
            current = this.find(matches, key);
            if (!current || current.value === '') {
                matches.push({
                    key: key,
                    value: params[key]
                });
            }
        }

        matches.forEach(function (item) {
            var current = this.find(this.routeParams, item.key);
            if (current) {
                escape.push({
                    key: '<' + current.key + '>',
                    value: item.value
                });
                delete params[item.name];
            } else if (this.find(this.paramRules, item.key)) {
                params[item.key] = item.value;
            }
        }.bind(this));


        if (this.routeParams.length) {
            route = this.escape(this.route, escape);
        } else {
            route = this.route;
        }

        result.push(route);
        result.push(params);

        return result;
    }
142421
private static String encodeExampleForUrl(Object example) {
        try {
            return URLEncoder.encode(String.valueOf(example), "UTF-8");
        } catch (UnsupportedEncodingException exception) {
            throw new RuntimeException(exception);
        }
    }
1341067
function parseEntryUrl(entry) {
	const parseUrl = require('url').parse;
	var parsed;

	// asset type
	entry.type = 'other';

	if (entry.url.indexOf('data:') !== 0) {
		// @see http://nodejs.org/api/url.html#url_url
		parsed = parseUrl(entry.url) || {};

		entry.protocol = parsed.protocol.replace(':', '');
		entry.domain = parsed.hostname;
		entry.query = parsed.query;

		if (entry.protocol === 'https') {
			entry.isSSL = true;
		}
	}
	else {
		// base64 encoded data
		entry.domain = false;
		entry.protocol = false;
		entry.isBase64 = true;
	}

	return entry;
}
974679
function url(queryString) {
  queryString = decodeURIComponent(queryString);
  queryString = queryString.split('&');
  return queryString.reduce((ret, url) => {
    url = url.split('=');
    var key = url[0];
    var val = url[1];

    // EXAMPLE: key[]=bar&key[]=world =>
    //  ret = { key: ['bar', 'world'] }
    if(key.slice(-2) === '[]') {
      key = key.slice(0, -2);
      ret[key] ? ret[key].push(val) : (ret[key] = [val]);

      // EXAMPLE: key[foo]=bar&key[hello]=world =>
      //  ret = { key: {foo: 'bar', hello: 'world'} }
    } else if(key.match(/\[\w+\]$/)) {
      let keys = key.split(/\[|\]/);
      let subkey = keys[1];
      key = keys[0];

      if(!ret[key]) ret[key] = {};
      ret[key][subkey] = val;
    } else {
      ret[key] = val;
    }
    return ret;
  }, {});
}
320922
function parseUrl(wpUrl) { //from node-wordpress
  var urlParts, secure;

  // allow URLs without a protocol
  if ( !(/\w+:\/\//.test( wpUrl ) ) ) {
    wpUrl = "http://" + wpUrl;
  }
  urlParts = url.parse( wpUrl );
  secure = urlParts.protocol === "https:";

  return {
    host: urlParts.hostname,
    port: urlParts.port || (secure ? 443 : 80),
    path: urlParts.path.replace( /\/+$/, "" ) + "/xmlrpc.php",
    secure: secure
  };
}
1169863
def parse(self, url):
        
        parsed_url = urlparse.urlparse(url)
        try:
            default_config = self.CONFIG[parsed_url.scheme]
        except KeyError:
            raise ValueError(
                'unrecognised URL scheme for {}: {}'.format(
                    self.__class__.__name__, url))
        handler = self.get_handler_for_scheme(parsed_url.scheme)
        config = copy.deepcopy(default_config)
        return handler(parsed_url, config)
1188080
function parse(url) {
  ['?', '#'].forEach(function(separator) {
    var index = url.indexOf(separator);
    if (index !== -1) url = url.substring(0, index);
  });
  return url;
}
569650
function parseUrlOrigin(url) {
   // url could be domain-relative
   // url could give a domain

   // cross origin means:
   //    same domain
   //    same port
   //    some protocol
   // so, same everything up to the first (single) slash 
   // if such is given
   //
   // can ignore everything after that   
   
   var URL_HOST_PATTERN = /(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/,

         // if no match, use an empty array so that
         // subexpressions 1,2,3 are all undefined
         // and will ultimately return all empty
         // strings as the parse result:
       urlHostMatch = URL_HOST_PATTERN.exec(url) || [];
   
   return {
      protocol:   urlHostMatch[1] || '',
      host:       urlHostMatch[2] || '',
      port:       urlHostMatch[3] || ''
   };
}
884097
def url_spec(transmute_path, handler, *args, **kwargs):
    
    p = _to_tornado_pattern(transmute_path)
    for m in METHODS:
        method = getattr(handler, m)
        if hasattr(method, "transmute_func"):
            method.transmute_func.paths.add(transmute_path)
    return tornado.web.URLSpec(
        p, handler,
        *args, **kwargs
    )
134055
public function parseRequestedURL()
    {
        // This is the re-constructions of teh proper URL.
        // 1. Schema
        $url = $this->app->getConfig('atk/base_url', null);
        if (is_null($url)) {
            // Detect it
            $url = 'http';
            $https = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || $_SERVER['SERVER_PORT'] == 443;
            if ($https) {
                $url .= 's';
            }

            // 2. Continue building. We are adding hostname next and port.
            $url .= '://'.$_SERVER['SERVER_NAME'];
            //if($_SERVER["SERVER_PORT"]!="80")$url .= ":".$_SERVER['SERVER_PORT'];
            if (($_SERVER['SERVER_PORT'] == '80' && !$https) || ($_SERVER['SERVER_PORT'] == '443' && $https)) {
                ;
            } else {
                $url .= ':'.$_SERVER['SERVER_PORT'];
            }
        }

        // We have now arrived at base_url as defined
        $this->base_url = $url;

        // 3. Next we need a base_part of our URL. There are many different
        // variables and approaches we tried it, REDIRECT_URL_ROOT, REDIRECT_URL,
        // etc, however most reliable is $this->unix_dirname(SCRIPT_NAME)
        $path = $this->unix_dirname($_SERVER['SCRIPT_NAME']);
        if (substr($path, -1) != '/') {
            $path .= '/';
        }

        // We have now arrived at base_path as defined
        $this->base_path = $path;

        // 4. We now look at RequestURI and extract base_path from the beginning
        if (isset($_GET['page'])) {
            $page = $_GET['page'];
            $this->page = $page;
        } else {
            $request_uri = $this->getRequestURI();
            if (strpos($request_uri, $path) !== 0) {
                throw $this->exception('URL matching problem')
                    ->addMoreInfo('RequestURI', $request_uri)
                    ->addMoreInfo('BasePath', $path);
            }
            $page = substr($request_uri, strlen($path));
            if (!$page) {
                $page = 'index';
            }

            // Preserve actual page
            $this->page = $page;

            // Remove postfix from page if any
            $page = preg_replace('/\..*$/', '', $page);
            $page = preg_replace('/\/$/', '', $page);
            $page = str_replace('/', '_', $page);

            if (substr($page, -1) == '_') {
                $page = substr($page, 0, -1);
            }
        }

        if (strpos($page, '.') !== false) {
            throw $this->exception('Page may not contain periods (.)')
            ->addMoreInfo('page', $page);
        }

        // We have now arrived at the page as per specification.
        $this->app->page = str_replace('/', '_', $page);

        $this->template_filename = $this->app->page;
        if (substr($this->template_filename, -1) == '/') {
            $this->template_filename .= 'index';
        }
    }
447811
def parse_url_rules(urls_fp):
    """"""
    url_rules = []
    for line in urls_fp:
        re_url = line.strip()
        if re_url:
            url_rules.append({'str': re_url, 're': re.compile(re_url)})
    return url_rules