Checking a RegEx Pattern Against an Array of Strings

PHPPosted on

Checking multiple strings against the same pattern is a common task in development. Usually, we use multiple preg_match for checking values, however, PHP provides a nice function that allows us to provide an array to the checker.

The “Old” Way

Let’s say we need to check if the request’s URI contains a specific keyword. Now, to make sure we need to check two variables $_SERVER[‘HTTP_REFERER’] and $_SERVER[‘REQUEST_URI’]. With the old way our check would look like this:

if (preg_match('/keyword|other/', $_SERVER['HTTP_REFERER']) || preg_match('/keyword|other/', $_SERVER['REQUEST_URI'])) {
    // Perform action
}

The “New” Way

Of course, this is not new, but it still surprising how many things we miss in daily development. We often find build-in PHP solutions when we face with a specific problem. So, let’s see how to match the same pattern with an array of strings.

if (preg_grep('/keyword|other/', [$_SERVER['HTTP_REFERER'], $_SERVER['REQUEST_URI']])) {
    //  Perform action
}

The big advantage is that we don’t need to “chain” preg_match functions, but we can keep the condition cleaner. There is not a big difference when you compare two strings only, but imagine when you need to check a bigger set of values where you need to perform this regex call.

You can find the documentation of preg_grep here.

Need a web developer? Maybe we can help, get in touch!

Looking for web dev job?
You can check them on Jooble.

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in PHP category