Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_match if pattern is a variable

Tags:

php

preg-match

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)){
  .......
}
like image 636
Daniele Palombetta Avatar asked Sep 01 '25 03:09

Daniele Palombetta


1 Answers

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) {
}
like image 152
Ja͢ck Avatar answered Sep 02 '25 17:09

Ja͢ck