i am trying to match all the domain including www using regex and replacing with preg_replace
Like
$oldomain = "example.com";
$newdomain = "www.example.net";
$string = "example.com, www.example.com, something.example.com, test.example.net, bla bla bla https://example.com etc etc"
preg_replace("#(www.?).#".$oldomain, $newdomain, $string);
So it will search for example.com and www.example.com and it will replace that with www.example.net
example.com -> www.example.net
www.example.com -> www.example.net
Update :
(www.?)*example.com - https://regex101.com/r/zOQBQD/1
CodePudding user response:
. is a special character in regex meaning any single character, excluding new lines. That needs to be escaped or in a character class.
# is your delimiter so your regex must be inside both of those.
* is a quantifier meaning the preceding character/group can occur zero or more times
You probably want something close to this:
preg_replace("#(www[.])?{$oldomain}#", $newdomain, $string);
{$oldomain} also is not regex, that is PHP syntax for the variable in double quotes to be expanded. Could also be written as:
preg_replace('#(www[.])?' . $oldomain . '#', $newdomain, $string);
You actually also should escape the domain for special chars so:
preg_replace('#(www[.])?' . preg_quote($oldomain, '#') . '#', $newdomain, $string);
is likely what you'll really want.
Regex101 as well: https://regex101.com/r/gwxyw1/1
