I have a site on a staging and production server. Staging address is "www-staging.example.com" while production is just "www.example.com".
Using PHP, I need to be able to detect the "www" portion, and check if it's "www-staging" or not. This also must work regardless of if the URL includes the protocol bit "http://".
input: "www-staging.example.com" || "http://www-staging.example.com" || "https://www-staging.example.com" || www-staging.example.com/a/directory"
Expected Output: true.
input: "www.example.com" || "http://www.example.com" || "https://www.example.com" || example.com/a/directory
Expected Output: false.
My initial approach was to use parse_url()
, however that does not parse the 'www-' component.
This seems like a job for... Regular expression (?:wo)?man!
Well, under certain conditions. Namely:
example.com
-- this won't work if you need it across multiple sites, though that functionality isn't hard to implement.Anyway, this should do it:
preg_match('^(?:https?:\/\/)?www(?:-staging)?\.example\.com\/', $url)
Of course, replace example\.com
with your actual domain name, with .
escaped as \.
.
If you don't want to put that regex in another, and don't plan on getting the specific match, you can simplify it a bit:
preg_match('^(https?:\/\/)?www(-staging)?\.example\.com\/', $url)
It ought to work the same, though I'm too tired and not experienced with PHP enough to say for sure.
Demo.