Mehul Kumar
Mehul Kumar

Reputation: 447

Replace all domain including subdomain name using PHP with Regex

I am using preg_replace or str_replace in PHP to replace all the domain name including www

$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain= "example.com";
$newdomain = "stackoverflow.com";

$output = str_replace($olddomain, $newdomain, $string);
$output = preg_replace('#(www[.])?[.]' . $olddomain. '#', $newdomain, $body);

echo $output;

My expectation:

https://example.com -> https://stackoverflow.com

https://www.example.com -> https://stackoverflow.com

https://subdomain.example.com -> https://subdomain.example.com

Upvotes: 2

Views: 251

Answers (4)

Sted
Sted

Reputation: 103

With Array and Regex

$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain = ["example.com", 'www\.'];
$newdomain = ["stackoverflow.com", ''];

$output = preg_replace('#https://(' . implode('|', $olddomain) . ')#', 'https://' . $newdomain[0], $string);
$output = preg_replace('#(' . $olddomain[1] . ')#', $newdomain[1], $output);

echo $output;

Upvotes: 1

Stellan Coder
Stellan Coder

Reputation: 313

Without using Regex

$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain= "example.com";
$newdomain = "stackoverflow.com";

$parts = explode(",", $string);
$new_parts = [];

foreach ($parts as $part) {
    $new_parts[] = str_replace(['https://', 'http://', $olddomain], ['https://', 'http://', $newdomain], $part);
}

$output = implode(",", $new_parts);

echo $output;

Return

https://stackoverflow.com, https://www.stackoverflow.com, https://subdomain.example.com 

Upvotes: 1

SYdeted
SYdeted

Reputation: 21

preg_replace with regex.

$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain= "example.com";
$newdomain = "stackoverflow.com";

$output = preg_replace('#(https://(www\.)?)' . $olddomain. '#', '$1' . $newdomain, $string);

echo $output;

Output :

https://stackoverflow.com, https://www.stackoverflow.com, https://subdomain.example.com 

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94642

No need for a regex, just pass the www. with the other change in into str_replace(). Remember str_replace() accepts an array of things to "change from" and "change to".

$string = ' https://example.com, https://www.example.com, https://subdomain.example.com ';
$olddomain = ["example.com",'www.'];
$newdomain = ["stackoverflow.com", ''];

$output = str_replace($olddomain, $newdomain, $string);
echo $output;

RESULT

 https://stackoverflow.com, https://stackoverflow.com, https://subdomain.stackoverflow.com 

Upvotes: 0

Related Questions