If you take a look at your pattern, it's this
/^http(s)?://(([a-z]+)\.)*stackoverflow.com/
The delimiter is used as a matching character, and if you had errors turned on, you'd get a "Unknown modifier" error. So first tip: TURN ERROR REPORTING ON!
To fix it, try using a different delimiter, e.g. {}
, as it's easier to read than loads of leaning toothpicks...
{^http(s)?://(([a-z]+)\.)*stackoverflow.com}
The other problem is the dot in the $domain
becomes a wildcard match - anytime you insert unknown data into a regex, get in the habit of using preg_quote to escape it, e.g.
$pattern = "{^http(s)?://(([a-z]+)\.)*" . preg_quote($domain, '{') . "}";
(Note - nice catch from stema in the comments: if you use a different delimiter, you must pass that preg_quote. It's clever enough to spot paired delimiters, so if you pass {
it will also escape }
.)