John Davidson

php - Replace www in URL with a pattern (wildcard subdomain)


Is there a way to replace

with this:

Which means "www" will be replaced by the name of the business. It should be quite simple but I have no idea how to accomplish this.

My Answer:
replacing "www" with a wildcard subdomain in a URL using PHP can be achieved with the following code:

$url = "";
$pattern = '/www\.(.*)\.com/';
$replacement = '$';

$newUrl = preg_replace($pattern, $replacement, $url);

echo $newUrl;

This code uses a regular expression to match the "www" subdomain in the URL and replace it with a wildcard subdomain. The `$1` in the replacement string refers to the wildcard subdomain captured by the regular expression.

Rate this post

5 of 5 based on 9475 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us