rmaspero
rmaspero

Reputation: 633

URL Parsing into Database

I have a form in which users can input a URL. Now obviously they some will put in www.example.com/path or example.com/path or http://www.example.com/path or even http://example.com/path.

What I want to do is to extract the whole URL host and path ect.. and put it in a standard form into my database. So no matter how it is formatted in the input they all have the same formatting in the database.

so the inputs go to outputs like below

www.example.com/path -> http://www.example.com/path
example.com/path -> http://www.example.com/path
http://www.example.com/path -> http://www.example.com/path
http://example.com/path ->http://www.example.com/path

Upvotes: 1

Views: 180

Answers (2)

Sanjeev Chauhan
Sanjeev Chauhan

Reputation: 4097

Find below example:

function updateUrl($url) {  
    if (strpos($url, '://')=== false && strpos($url, 'www.')=== false) {
        $url = 'http://www.' . $url;
    }
    else if(strpos($url, '://')=== false) {
        $url = 'http://' . $url;
    }
    else if(strpos($url, 'www.')=== false) {
        $url = str_replace('http://','http://www.',$url);
    }
    else {
        $url = $url;
    }
    return $url;
}
$url = "http://example.com/path";
echo updateUrl($url);

Upvotes: 1

Verne Jules
Verne Jules

Reputation: 80

Use regex for the URL's then use preg_match when validating it and specify PREG_OFFSET_CAPTURE to make it into an array of the values in the matches. Then manipulate it to a string that satisfies your format.

Upvotes: 2

Related Questions