Backend Development 5 min read

Understanding PHP preg_filter(): Syntax, Parameters, and Practical Example

This article explains PHP's preg_filter() function, its equivalence to preg_replace(), details each parameter, usage notes, and provides a complete example with code and output to illustrate how it performs regex search-and-replace returning only matched results.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding PHP preg_filter(): Syntax, Parameters, and Practical Example

The preg_filter() function in PHP executes a regular‑expression search and replace, but unlike preg_replace() it returns only the parts of the subject that match the pattern (after any replacements).

Its signature is preg_filter(mixed $pattern, mixed $replacement, mixed $subject, int $limit = -1, int &$count = null) . The function behaves the same as preg_replace() except for the return value.

Parameters :

pattern : The regex pattern(s) to search for. Can be a string or an array of strings, with optional PCRE modifiers.

replacement : The replacement string(s). Supports back‑references like \1 or $1 . If arrays are used, each pattern is paired with the corresponding replacement.

subject : The string or array of strings to be processed.

limit : Maximum number of replacements per pattern (default -1 for unlimited).

count : Optional variable that receives the total number of replacements performed.

Return value : If subject is an array, an array of matched results is returned; otherwise a string is returned. If no matches are found, an empty array (for array subjects) or NULL (for string subjects) is returned.

Example :

Output :

preg_filter returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:3
    [4] => A:4
)

preg_replace returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:3
    [4] => A:4
)

The example demonstrates that preg_filter() returns only the elements where a pattern matched, while preg_replace() returns the full subject array with replacements applied.

backendphpregexstring replacementphp-functionspreg_filter
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.