format a url nicely in PHP

A pretty simple function, which formats a url nicely for display or use.

function nice_url($url) {

    if(!(strpos($url, "http://") === 0)
	&& !(strpos($url, "https://") === 0)) {

        $url = "http://$url";
    return $url;


Self explanatory really, and it works well in conjunction with the function to convert links into clickable hyper links.

[edit] 31 Jan 2012: Updated function as per comments. Now tests for “http” and “https” and is not case-sensitive. [/edit]

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

3 Responses to format a url nicely in PHP

  1. rabndon says:

    There’s a bug with this code. If the URL contains “case-sensitive” data (such as going to a page called “Home.php”) this code causes all letters to be lower-case. It’d be better to check the first seven and eight characters of a URL, lower-case that, and see if it matches either “http://” or “https://”.

  2. Hey,

    Thanks a ton for this, it was a good starting place for something I’m working on.

    A Note: while strtolower on a url is nice. Most web servers (LAMP) ARE case sensitive. So, I would only strtolower to domain name.



    • Cameron says:

      Thanks Joey

      I’ve updated the example, and removed the strtolower entirely. I haven’t worried about setting the domain to lower-case, as this is meant to be a simplistic example. I figure the user can handle that to begin with when providing the URL to the function.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: