PHP normalizes remote url

Is there any quick feature that will convert: HtTp://www.ExAmPle.com/blahtoHtTp://www.ExAmPle.com/blah

Basically, I want lowercase letters to be case insensitive to parts of the URL.

+3
source share
4 answers

Since you asked for “fast”, here is one liner that does the job:

$url = 'HtTp://User:Pass@www.ExAmPle.com:80/Blah';

echo preg_replace_callback(
  '#(^[a-z]+://)(.+@)?([^/]+)(.*)$#i',
  create_function('$m',
                  'return strtolower($m[1]).$m[2].strtolower($m[3]).$m[4];'),
  $url);

Outputs:

http://User:Pass@www.example.com:80/Blah

EDIT / ADD:

I tested, and this version is about 55% faster than using preg_replace_callback with an anonymous function:

echo preg_replace(
  '#(^[a-z]+://)(.+@)?([^/]+)(.*)$#ei',
  "strtolower('\\1').'\\2'.strtolower('\\3').'\\4'",
  $url);
+3
source

No, you have to write the code for it yourself.

But you can use parse_url()to split the URL into its parts.

+5
source

, , @ThiefMaster:

DEMO

function urltolower($url){
  if (($_url = parse_url($url)) !== false){ // valid url
    $newUrl = strtolower($_url['scheme']) . "://";
    if ($_url['user'] && $_url['pass'])
      $newUrl .= $_url['user'] . ":" . $_url['pass'] . "@";
    $newUrl .= strtolower($_url['host']) . $_url['path'];
    if ($_url['query'])
      $newUrl .= "?" . $_url['query'];
    if ($_url['fragment'])
      $newUrl .= "#" . $_url['fragment'];
    return $newUrl;
  }
  return $url; // could return false if you'd like
}

Note: not tested for battle, but this should get you going.

+1
source

All Articles