Daniele Palombetta
Daniele Palombetta

Reputation: 43

PHP preg_match if pattern is a variable

If the pattern is a variable in preg_match, it's correct this syntax for use the delimiters?

if (!preg_match("/{$_SERVER["SERVER_NAME"]}/",$variable)){
  .......
}

Upvotes: 4

Views: 7883

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173562

The right way to handle this is by using preg_quote() to make sure characters with a special meaning in regular expressions are properly escaped:

$pattern = '/' . preg_quote($_SERVER['SERVER_NAME'], '/') . '/';
if (!preg_match($pattern, $variable)) {
}

Of course, this in itself is not a very useful expression, because you can also write this:

if (strpos($variable, $_SERVER['SERVER_NAME']) === false) {
}

Upvotes: 6

Related Questions