hillz
hillz

Reputation: 547

How to use preg_match to match more than one variables?

I have a lot of variables that I want to validate with the same pattern, they look like this:

$pattern = "/[$()`]/"
$one
$two
$three
etc...

Instead of writing it like this:

if (!preg_match($pattern, $one) && !preg_match($pattern, $two) && !preg_match($pattern, $three)) {
// do stuff
}

Is there a simpler way of validating those variables all at once ?

Upvotes: 1

Views: 769

Answers (2)

Karol Gasienica
Karol Gasienica

Reputation: 2904

What about it:

$tests = array($one, $two, $three);
$tests_count = count($tests);

if (count(preg_grep('/[$()`]/', $tests, PREG_GREP_INVERT)) == $tests_count) {
    // some stuff
}

If you want to do some stuff if any of tests fails, it can be:

count(preg_grep('/[$()`]/', $tests, PREG_GREP_INVERT)) > 0)

Upvotes: 0

user6533277
user6533277

Reputation:

<?php
$array= array($one, $two, $three);

if (in_array("$()`", $array))
  {
  echo "Match found";
  }
else
  {
  echo "Match not found";
  }
?>

I hope this will work for you

Upvotes: 1

Related Questions