John Davidson

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

0 comments
Message:


Is there a way to replace


www.domain.com/new-mexico/albuquerque/businessname-513526.html


with this:


businessname.domain.com/new-mexico/albuquerque/businessname-513526.html


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:

php
$url = "www.domain.com/new-mexico/albuquerque/businessname-513526.html";
$pattern = '/www\.(.*)\.com/';
$replacement = '$1.domain.com';

$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

4 of 5 based on 6241 votes

Comments




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