I want to use preg_match() in my code, but the result is nothing ... (or null or empty ?)
$domain = "stackoverflow.com";
$uriToTest = "http://stackoverflow.com/";
$pattern = "/^http(s)?://(([a-z]+)\.)*".$domain."/";
echo preg_match($pattern, $uriToTest);
What is the problem?
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 }.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With