The preg_filter Function

The preg_filter function performs search and replace in a string or array of strings by regular expression. Unlike preg_replace, it returns only those elements where a match was found. The first parameter accepts a regular expression, the second - a replacement string, the third - a string or array to process. The fourth optional parameter can specify the maximum number of replacements in each element (default is -1, which means "no limit"). The fifth optional parameter specifies the variable into which the number of performed replacements will be written.

Syntax

phppreg_filter(pattern, replacement, subject, [limit = -1], [count]);

Example

Let's replace all digits in the string with the 'X' character:

php<?php
  $res = preg_filter('/\d/', 'X', 'a1b2c3');
  var_dump($res);
?>

Code execution result:

php'aXbXcX'

Example

Let's process an array of strings, replacing digits with '#':

php<?php
  $res = preg_filter('/\d/', '#', ['a1', 'b2', 'c', 'd4']);
  var_dump($res);
?>

Code execution result:

php['a#', 'b#', 'd#']

Example

Let's demonstrate the difference from preg_replace:

php<?php
  $input = ['a1', 'b2', 'c', 'd4'];
  $res_filter = preg_filter('/\d/', '#', $input);
  $res_replace = preg_replace('/\d/', '#', $input);
  echo "Filter result: ";
  var_dump($res_filter);
  echo "Replace result: ";
  var_dump($res_replace);
?>

Code execution result:

phpFilter result: ['a#', 'b#', 'd#']
Replace result: ['a#', 'b#', 'c', 'd#']

See Also

  • the preg_replace function,
    which performs replacement by regular expression
  • the preg_match function,
    which checks for a match with a regular expression