Remove slashes and the http from a URL – PHP Example

Remove Slashes From A URL

The PHP example below takes an encoded URL, decodes it, then strips away the slashes and http, leaving only the domain.com to deal with.

The Snip:

preg_replace( "#^[^:/.]*[:/]+#i", "", preg_replace( "{/$}", "", urldecode( $website ) ) );
 

Breaking It Down

It starts by decoding an encoded URL: It turns, http%3A%2F%2Ftechnerdia.com%2F into https://technerdia.com

Why is the URL encoded? I use this snip when pulling URLs from a database. The snip still works if the URL isn’t encoded.

Decode the Encoded URL

$website = "http%3A%2F%2Ftechnerdia.com%2F";
$website = urldecode( $website );
echo $website;
/* Result: https://technerdia.com/ */

Removing Trailing Slash from the URL

$website = "https://technerdia.com/";
$website = preg_replace( "{/$}", "", $website );
echo $website;
/* Result: https://technerdia.com */

Remove the https:// from the URL

$website = "https://technerdia.com";
$website = preg_replace( "#^[^:/.]*[:/]+#i", "", $website );
echo $website;
/* Result: technerdia.com */

That’s It!

Make It All One Line
You can stack it all together and simply echo the line, instead of typing all that out.

$website = "http%3A%2F%2Ftechnerdia.com%2F";
echo preg_replace( "#^[^:/.]*[:/]+#i", "", preg_replace( "{/$}", "", urldecode( $website ) ) );
/* Result: technerdia.com */
 

This little snip of code is a time saver, that’s its job!

When you insert URL’s into a database and also need the domain.com inserted, use this to strip away the garbage rather than typing in the domain.com each time. On the flip side, maybe you only have the URL and need the domain.com, which is typical in APIs or building URLs for sites like Alexa and Site Explorer Tools, and of course many other reasons.

Comments are closed.