W3docs

Understanding PHP's preg_filter Function

The preg_filter function in PHP is a versatile tool for working with regular expressions. It allows developers to search for and replace text that matches a

The preg_filter function in PHP searches a string (or array of strings) for text that matches a regular expression and replaces it. Its defining feature is that it only returns the entries where a match occurred — non-matching entries are discarded. This makes it ideal for jobs where you want to search, replace, and filter in a single step.

If you have used preg_replace, preg_filter will feel familiar: the syntax is identical. The one behavioral difference — what happens to non-matching subjects — is what makes preg_filter worth reaching for, and it's the focus of this page.

In this article, we'll cover the syntax, the parameters, how preg_filter differs from preg_replace, and the most common use cases, each with a runnable example.

Syntax and Parameters

The syntax of the preg_filter function is as follows:

PHP preg_filter syntax

preg_filter(pattern, replacement, subject [, limit [, count]])

The parameters are as follows:

  • pattern: This is a regular expression pattern that specifies the text you want to search for.
  • replacement: This is the text that will replace the matching text in the subject.
  • subject: This is the string that you want to search and replace text in.
  • limit (optional): The maximum number of replacements per subject string. Defaults to -1 (no limit).
  • count (optional): A variable passed by reference that will be filled with the total number of replacements made.

The pattern, replacement, and subject arguments can each be a single value or an array, exactly as with preg_replace. The return value is a string when subject is a string, and an array when subject is an array.

preg_filter vs. preg_replace

The two functions take the same arguments and do the same search-and-replace work. The difference is what they return when a subject does not match the pattern:

  • preg_replace returns the subject unchanged.
  • preg_filter returns null for a string subject, and omits the entry entirely for an array subject.
<?php
$input = ["123", "abc", "456"];

// preg_replace keeps every element, matched or not.
print_r(preg_replace("/\d+/", "[num]", $input));
// Array ( [0] => [num] [1] => abc [2] => [num] )

// preg_filter drops the non-matching "abc".
print_r(preg_filter("/\d+/", "[num]", $input));
// Array ( [0] => [num] [2] => [num] )
?>

Notice that preg_filter preserves the original keys (0 and 2) — it does not re-index the array.

Use Cases

preg_filter is most useful when you need to search, replace, and filter at the same time. Common use cases include:

  • Filtering arrays: Pass an array of strings and get back only the elements that matched the pattern.
  • Removing HTML tags: Strip tags from strings or arrays of strings.
  • Extracting and reformatting: Replace matched text while discarding entries that contain nothing of interest.

Example: Removing HTML tags

In this example, we'll use preg_filter to remove HTML tags from a string:

PHP preg_filter example

php— editable, runs on the server

In this example, we're using the regular expression pattern /<[^>]+>/ to match all HTML tags in the $html string. The replacement parameter is set to an empty string, so the matching text is removed. The resulting text is then stored in the $text variable and echoed to the screen.

Example: Filtering array elements

preg_filter shines when working with arrays because it removes non-matching elements:

<?php
$items = ["apple", "banana", "apricot", "cherry"];
$filtered = preg_filter("/^a/", "A", $items);
print_r($filtered);
// Outputs:
// Array
// (
//     [0] => Apple
//     [2] => Apricot
// )
?>

In this example, preg_filter replaces the starting "a" with "A" but automatically removes "banana" and "cherry" because they don't match the pattern. The kept elements keep their original keys (0 and 2).

Counting replacements with the count parameter

The optional fifth parameter is filled by reference with the number of replacements made, which is handy for reporting or for branching on whether anything matched:

<?php
$subject = "Order #42 and order #7";
$result = preg_filter("/#(\d+)/", "[$1]", $subject, -1, $count);
echo $result . "\n";   // Order [42] and order [7]
echo $count . "\n";    // 2
?>

Here $1 in the replacement is a back-reference to the first capture group. Two matches were replaced, so $count is 2.

Conclusion

preg_filter performs a regular-expression search and replace just like preg_replace, but discards subjects that don't match — returning null for strings and dropping non-matching elements from arrays. That makes it the right choice when filtering and replacing belong together in one step.

To go deeper into PHP's regex toolkit, see preg_match for testing a single match, preg_match_all for finding every match, preg_split for splitting strings, and preg_replace_callback when the replacement needs to be computed in code.

Practice

Practice
What is the function of preg_filter in PHP?
What is the function of preg_filter in PHP?
Was this page helpful?