PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Thu Dec 14, 2017 7:59 am

All times are UTC - 5 hours




Post new topic This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Regex To Grab Domain
PostPosted: Tue Oct 17, 2017 4:31 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 179
Folks,

I need a regex to extract the domain name from any url. No matter what the url looks like. Whether it has more than one dot (2nd level, 3rd level, 4th level, 5th level, etc. level domain) and whether or not it has the http://, https://, http://www., etc.).
In short, it must work on any url in the world. No matter what format the url is in aslong as the url is a valid one. No matter how good, ugly, short or long the url is.
I am spoiled for choice as too many samples are provided here and I don't know which one will best suit my purpose:
https://stackoverflow.com/questions/569 ... e-from-url

Q1. Which one is your best pick for my purpose and why that one over the others ?

Q2. Would you use the parse_url over all the regex codes mentioned here:
https://stackoverflow.com/questions/569 ... e-from-url
If parse_url is fine then why did those programmers in that above mentioned link bother with regex ?

Is my parse_url code ok ?

Code:
    <?php

    include 'config.php';

    $url = "http://one.com/1.php";
    $domain = parse_url($url, PHP_URL_HOST);
    echo $domain;

    $url = "http://two.com/2.htm";
    $domain = parse_url($url, PHP_URL_HOST);
    echo $domain;


    $domain = parse_url("http://three.com/3.html", PHP_URL_HOST);
    echo $domain;


    $domain = parse_url("http://four.com/4.shtm", PHP_URL_HOST);
    echo $domain;


    $domain = parse_url('http://five.com/5.shtml', PHP_URL_HOST);
    echo $domain;

    $domain = parse_url('http://usr:pss@example.com:81/mypath/myfile.html?
    a=b&b[]=2&b[]=3#myfragment', PHP_URL_HOST);
    echo $domain;

    ?>


Notice how many types of urls I tested with parse_url. Parse_url seems to manage to grab the domain as I want.


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 18 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group