XanT XanT - 4 months ago 10
PHP Question

Replace optional subdomain

I am doing some post-processing and on a specific link using

preg_replace
to see if a link has a subdomain and if it does, replace it and if it does not - add a specific subdomain in. My regex currently adds the subdomain in if it does not exist however if it does exist already it add's it twice.

Desired result examples

Input: http://somesubdomain.example.com/
Output: http://newsubdomain.example.com/

Input: http://example.com/
Output http://newsubdomain.example.com/

What I am currently using:

preg_replace('/(?:.)example\.com\/game\/([a-zA-Z0-9-_,.]+)/','specialsubdomain.example.com/game/$1', $output);


So if there is a subdomain, replace it, if there is not - insert it.

Thanks a lot.

Answer

Describe the eventual subdomain in a non-capturing group and make it optional:

$pattern = '~(?:[^/]*\.)?(example\.com/game/[\w,.-]+)~';
$result = preg_replace($pattern, 'specialsubdomain.$1', $output);