Skip to content
PHP Logo

What are the alternative methods, such as regex or explode/implode, for removing 'www.' from a URL output in PHP?

When working with URLs in PHP, you may need to remove the 'www.' prefix for various reasons, such as standardizing URLs or improving user experience. One way to achieve this is by using regular expressions (regex) to search for and replace the 'www.' substring. Another method is to split the URL into an array using explode(), remove the 'www.' element, and then rejoin the array using implode().

php
// Using regex to remove 'www.' from a URL
$url = "http://www.example.com";
$cleaned_url = preg_replace('/^(https?:\/\/)?(www\.)?/', '$1', $url);
echo $cleaned_url;

// Using explode/implode to remove 'www.' from a URL
$url = "http://www.example.com";
$url_parts = explode(".", $url);
if($url_parts[0] == "www") {
    array_shift($url_parts);
}
$cleaned_url = implode(".", $url_parts);
echo $cleaned_url;