format a url nicely in PHP
Sunday, June 6th, 2010 3 Comments
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]
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://”.
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.
Thanks!
Joey
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.