How do I remove a domain from a string in PHP?

November 15, 2012

This doesn’t feel like it should be that hard, and luckily it’s not! However, some of the more common ways I found had been commented on being rather unreliable.  Most people recommend an easy str_replace, removing the specified domain and replacing it with an empty string.  But what if you don’t know your domain yet, what if your still in development? No one wants to go back and change that…

So here’s a rather brilliant little combo of exploding and replacing that will work regardless of what the domain is. Done and done.

$fileurl = get_field('pdf');
$fileurlexplode = explode('.com/', $fileurl);
$removedomain = $fileurlexplode [0].'.com/';
$fileurl = str_replace($removedomain , "",$fileurl); ?>

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive