Current Location: Home> Latest Articles> array_filter() is used to implement complex matching filtering with regular expressions

array_filter() is used to implement complex matching filtering with regular expressions

M66 2025-06-04

In PHP development, we often need to filter out elements that meet specific conditions from an array. array_filter() is a powerful tool to deal with this requirement, and regular expressions can come in handy when you want to perform more complex matches (such as pattern recognition, keyword filtering, etc.).

This article will introduce how to use array_filter() with regular expressions to achieve more flexible array matching and filtering.

1. Introduction to array_filter()

array_filter() is a built-in function provided by PHP, which is used to filter elements in an array based on the return value of the callback function. The basic syntax is as follows:

 array_filter(array $array, ?callable $callback = null, int $mode = 0): array
  • $array : The original array to filter.

  • $callback : The callback function used to test each value of the array, returns true to reserve, and returns false to be removed.

  • $mode : Optional, to specify whether to pass in a key value, a key name, or both.

If $callback is not passed, array_filter() removes the values ​​equivalent to false in the array (such as 0 , false , '' , null , etc.).

2. Typical usage scenarios that combine regular expressions

The following are several typical scenarios. We will use array_filter() with preg_match() (regular matching function) to complete the filtering operation.

1. Filter strings containing specific keywords

Suppose we have a URL list and want to find the link that contains the login field:

 $urls = [
    'https://m66.net/login',
    'https://m66.net/register',
    'https://m66.net/user/profile',
    'https://m66.net/logout',
    'https://m66.net/help/login-guide'
];

$filtered = array_filter($urls, function($url) {
    return preg_match('/login/i', $url);
});

print_r($filtered);

Output result:

 Array
(
    [0] => https://m66.net/login
    [4] => https://m66.net/help/login-guide
)

Description: /login/i means matching a case-insensitive "login".

2. Filter out strings in mailbox format

 $data = [
    'john@example.com',
    'https://m66.net/contact',
    'not-an-email',
    'user@domain.net',
    'hello@m66.net'
];

$emails = array_filter($data, function($item) {
    return preg_match('/^[\w\.-]+@[\w\.-]+\.\w{2,}$/', $item);
});

print_r($emails);

Output result:

 Array
(
    [0] => john@example.com
    [3] => user@domain.net
    [4] => hello@m66.net
)

3. Match strings starting with numbers

 $items = ['123start', 'alpha', '42beta', 'm66.net', '99bottles'];

$startsWithDigit = array_filter($items, function($str) {
    return preg_match('/^\d/', $str);
});

print_r($startsWithDigit);

Output result:

 Array
(
    [0] => 123start
    [2] => 42beta
    [4] => 99bottles
)

3. Advanced skills: Multi-condition matching

You can also build more complex matching logic through combinations of regular expressions. For example, match URLs that contain both "login" and end with .net :

 $urls = [
    'https://m66.net/login',
    'https://m66.net/login-help.net',
    'https://m66.net/home',
    'https://m66.net/logout',
    'https://m66.net/login/info'
];

$matched = array_filter($urls, function($url) {
    return preg_match('/login.*\.net$/i', $url);
});

print_r($matched);

4. Things to note

  1. Regular expression efficiency problem : Complex regular expressions may affect performance when processing large arrays. It is recommended to cache intermediate results or optimize expressions.

  2. Unicode character matching : u modifier needs to be enabled, such as /pattern/u .

  3. Processing multi-dimensional arrays : For multi-dimensional arrays, array_filter() only processes one-dimensional by default. If deeper filtering is required, you can use recursive functions to handle it.

5. Summary

By combining array_filter() with preg_match() , PHP developers can easily implement complex array filtering logic. This method is not only concise in syntax, but also has high execution efficiency. It is suitable for various scenarios such as data cleaning, input verification, and URL filtering.

Mastering this skill will greatly improve your data processing capabilities in actual projects!