In PHP, preg_filter() runs a regular-expression replace like preg_replace(), but only keeps subjects that actually matched the pattern.
When $subject is an array, the result is an array of replaced strings for the items that matched (keys are preserved). When $subject is a string and nothing matches, the function returns null instead of the original string.
Syntax
Call preg_filter() with the values you need. Start with this line.
PHP
$result = preg_filter('/\d+/', '#', $subject);
Call
What it does
preg_filter('/\d+/', 'X', 'dog12')
Returns "dogX", because the digits matched.
preg_filter('/\d+/', 'X', 'bird')
Returns null, because the string has no digits.
preg_filter('/\d+/', 'X', ['cat', 'dog12'])
Returns an array with only the replaced "dogX" entry.
preg_filter() and preg_replace() use the same pattern, replacement, limit and count arguments. The difference is the return value: preg_replace() always returns every subject (changed or not), while preg_filter() drops non-matches.
Library declarations
PHP
preg_filter(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null
Parameters
Parameter
Description
pattern
Required. A PCRE pattern string such as /\d+/, or an array of patterns. Patterns use delimiters and optional flags.
replacement
Required. The replacement string (or array of strings). Backreferences like $1 are allowed.
subject
Required. The string or array of strings to search.
limit
Optional. Maximum replacements per subject. Default -1 means no limit.
count
Optional. Passed by reference. Receives how many replacements were made.
Return Value
Return Value
Description
string|array|null
For a string subject: the replaced string, or null if there was no match. For an array subject: an array of only the subjects that matched (after replacement). Returns null on error.
PHP Examples
Example 1 — Replace Digits in One String
Call preg_filter() on a short string that contains digits.
Only dog12 and fish3 contain digits, so only those keys remain.
Keys 1 and 3 are preserved from the original array.
cat and bird are dropped because they did not match.
Frequently Asked Questions
preg_filter() performs a regular-expression replace and returns only the subjects that matched. Non-matching string subjects become null; non-matching array items are omitted.
Both replace matches the same way. preg_replace() always returns every subject. preg_filter() returns only subjects that had a match, or null for a string that did not match.
When $subject is a single string and the pattern does not match, or when an error occurs. For arrays, non-matches are simply left out of the result array.
No. It returns a new value. Your original $subject variable stays the same unless you assign the result back to it.
Yes. The pattern, replacement, limit and count parameters work the same way. Only the filtering behavior of the return value is different.