PHP preg_filter() Function

PHP

PHP preg_filter() - Perform Regex Filter

The preg_filter() function in PHP offers a powerful way to perform regex-based search and replace operations while returning only the changed values. Unlike preg_replace(), it filters out any elements where no replacements were made β€” making it especially useful when you want to retrieve only the filtered results. In this tutorial, you will learn everything about preg_filter(), from its syntax and setup to practical examples, best practices, interview questions, and common pitfalls.

Prerequisites

  • Basic understanding of PHP programming
  • Familiarity with regular expressions (regex) syntax
  • PHP installed on your development machine (PHP 5.0.0+)

Setup Steps

  1. Make sure PHP is installed on your system. You can verify this by running php -v in your command line.
  2. Create a new PHP script file, for example, preg_filter_example.php.
  3. Use any text editor or IDE to write your PHP code implementing preg_filter().
  4. Run your script either in a browser via a local server (e.g., XAMPP, MAMP) or CLI (php preg_filter_example.php).

Understanding preg_filter()

preg_filter() performs a regular expression search and replaces matching parts in subject strings. It returns an array of only the elements where replacements were made. If no matches are found for an element, that element is omitted from the returned array (or NULL if the input was a string and no replacements occurred).

Syntax

preg_filter(
    string|array $pattern,
    string|array $replacement,
    string|array $subject,
    int $limit = -1,
    int &$count = null
): string|array|null
  • $pattern: Regular expression pattern(s).
  • $replacement: Replacement string(s).
  • $subject: Input string or array of strings to search and replace.
  • $limit: Maximum possible replacements per subject; default is -1 (no limit).
  • $count: If specified, sets this variable to the number of replacements done.

Examples

Example 1: Simple Replacement in a String

Replace all occurrences of digits with a hash (#) only if digits exist:

<?php
$pattern = '/\d+/';
$replacement = '#';
$subject = 'My number is 1234';

$result = preg_filter($pattern, $replacement, $subject);

echo $result;  // Output: My number is #
?>

Here, since digits are matched and replaced, preg_filter() returns the modified string.

Example 2: Array Input - Returning Only Changed Elements

Filter user input array, replacing email domains only if matched:

<?php
$emails = [
  'alice@example.com',
  'bob@test.com',
  'carol@sample.com',
  'dave@example.com'
];

$pattern = '/@example\.com$/';
$replacement = '@newdomain.com';

$result = preg_filter($pattern, $replacement, $emails);

print_r($result);
/* Output:
Array
(
    [0] => alice@newdomain.com
    [3] => dave@newdomain.com
)
*/
?>

Notice only emails from example.com are replaced and returned. Others (e.g., bob@test.com, carol@sample.com) are filtered out.

Example 3: Using Limit and Count

Replace at most 1 occurrence and get replacement count:

<?php
$names = ['John123', 'Mary456', 'Alex789'];
$pattern = '/\d+/';
$replacement = '';
$count = 0;

$result = preg_filter($pattern, $replacement, $names, 1, $count);

print_r($result);
echo "Replacements made: $count";
/* Output:
Array
(
    [0] => John
)
Replacements made: 1
*/
?>

Only the first element gets digits removed, and the rest are omitted as no replacements occurred.

Best Practices

  • Use preg_filter() when you want to get only the elements that have been modified β€” it's efficient for filtering changed data.
  • Always test your regex patterns separately to ensure they match the intended parts.
  • Specify the $limit parameter when you want to control the number of replacements per subject.
  • Use the reference $count parameter to track how many replacements occur, useful for debugging or logic branching.
  • Handle the return value cautiously: if a string subject is used and no replacements occur, preg_filter() returns NULL.

Common Mistakes

  • Expecting preg_filter() to return unmodified elements: It only returns replaced elements, so unmodified parts are filtered out.
  • Incorrect regex syntax: Mistyped patterns may cause no replacements or errors.
  • Forgetting the limit parameter: May cause unexpected multiple replacements.
  • Not checking for NULL return: When the subject is a string and no match found, the result is NULL, which can cause errors if not handled.
  • Mixing string and array inputs: Ensure the $pattern, $replacement, and $subject types correspond properly when used as arrays or strings.

Interview Questions

Junior Level

  • Q1: What does preg_filter() return if no matches are found in a string subject?
    A: It returns NULL if no replacements occur.
  • Q2: How is preg_filter() different from preg_replace()?
    A: preg_filter() returns only strings where replacements were made; preg_replace() returns all results.
  • Q3: Can preg_filter() work with arrays as inputs?
    A: Yes, it accepts both string and array inputs for patterns and subjects.
  • Q4: What is the default value of the $limit parameter?
    A: The default is -1, meaning unlimited replacements per subject.
  • Q5: What data type is expected for the $pattern argument?
    A: It expects a string or an array of regex pattern strings.

Mid Level

  • Q1: How does preg_filter() handle unmatched elements when the input is an array?
    A: It excludes unmatched elements from the returned array.
  • Q2: How would you use the $count parameter with preg_filter()?
    A: Pass it by reference to get the total replacements made during the call.
  • Q3: Can you provide an example scenario where preg_filter() is preferred over preg_replace()?
    A: Filtering and returning only emails where the domain was replaced in a mailing list.
  • Q4: What happens if you pass different types for $pattern and $replacement arrays of differing lengths?
    A: It’s undefined behavior; replacements may mismatch or trigger warnings.
  • Q5: Is it possible to perform case-insensitive replacements with preg_filter()?
    A: Yes, by adding modifiers like i in the regex pattern (e.g., /pattern/i).

Senior Level

  • Q1: How can the return value of preg_filter() impact the logic flow when processing string vs array inputs?
    A: For strings, it may return NULL if no replacements occur, requiring null checks, whereas for arrays it returns a filtered array without unmatched elements, affecting iteration and data consistency.
  • Q2: Describe a strategy to preserve the original keys of an associative array when using preg_filter().
    A: Since preg_filter() preserves original keys for replaced elements, you can rely on this behavior, but need to be cautious about missing keys due to filtered-out elements.
  • Q3: How would you combine preg_filter() with other PHP functions to create a pipeline of data filtering and transformation?
    A: Use preg_filter() to filter changed elements and then functions like array_map() or array_values() to normalize or further transform the filtered results.
  • Q4: What are the performance implications of using preg_filter() over preg_replace() in large datasets?
    A: preg_filter() may be more memory efficient if you only need changed data since it excludes unchanged items, reducing downstream processing, but the regex execution cost is similar.
  • Q5: How can misuse of regex patterns in preg_filter() lead to unexpected security issues, and how to mitigate them?
    A: Poorly constructed patterns can cause DoS (ReDoS) via catastrophic backtracking. To mitigate, carefully design regex, limit input sizes, and validate before filtering.

Frequently Asked Questions (FAQ)

  • Q: What does preg_filter() return if the replacement doesn’t change any character in the input string?
    A: It returns NULL if the subject is a string with no replacements.
  • Q: Can preg_filter() be used for multi-pattern replacements?
    A: Yes, by passing arrays of patterns and replacements.
  • Q: How to check how many replacements were made?
    A: Use the optional $count parameter passed by reference.
  • Q: Is preg_filter() case-sensitive by default?
    A: Yes, unless you add the i modifier in your regex pattern.
  • Q: What PHP versions support preg_filter()?
    A: It is supported in PHP 5.0.0 and later versions.

Conclusion

The PHP preg_filter() function is an excellent tool in the RegEx toolkit to perform regex-based search and replace operations while efficiently returning only those elements that underwent changes. By understanding its syntax, input-output behavior, limitations, and best practices, you can incorporate preg_filter() into your PHP application for cleaner and targeted string filtering. Whether filtering user inputs, emails, or any regex-based modifications, preg_filter() helps keep your data processing streamlined.