Quantcast
Channel: url
Viewing all articles
Browse latest Browse all 2

PHP and Javascript strip or replace "www" from URL

0
0

Just a handy and short code snippet to demonstrate how to strip or replace "www" from URL but not with "www.tld".

<?php
// Server side
$url = 'http://www.abc.com/?q=Hello+World&os=Win#content';

class

Test {
  function
getHostname($url) {
   
$parse = parse_url($url);
   
$host = preg_replace('/^www\.(.+\.)/', '$1', $parse['host']);
    return
$host;
  }
}

$test = new Test();
echo
$test->getHostname($url);
?>

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <!-- Client side -->
    <div id="url" style="display:none;"><?php echo $url; ?></div>

    <script>
    function getHostname(url) {
      var host = url.match('^(?:f|ht)tp(?:s)?\://([^/]+)')[1].toString();
      host = host.replace(/^www\.(.+\.)/, '$1');
      return host;
    }

    var url = document.getElementById('url').innerHTML;

    document.writeln('<br />');
    document.writeln(getHostname(url));
    </script>
  </body>
</html>


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images