Tuesday, June 16, 2026
HomeLanguagesPHP | preg_filter() Function

PHP | preg_filter() Function

The preg_filter() function is an inbuilt function in PHP which is used to perform a regular expression search and replace the text.

Syntax:

preg_filter( $pattern, $replacement, $subject, $limit, $count )

Parameters: This function accepts five parameters as mention above and describe below.

  • $pattern: This parameter contains an string element which is search for and it can be a string or array of string.
  • $replacement: It is mandatory parameter which specifies the string or an array with strings to replace.
  • $subject: The string or an array with strings to search and replace.
  • $limit: This parameter specifies the maximum possible replacements for each pattern.
  • $count: It is optional parameter which is used to fill with the number of replacements done.

Return Value: This function returns an array if the subject parameter is an array, or a string otherwise.

Below program illustrates the preg_filter() function in PHP:
Program 1:




<?php
  
// PHP program to illustrate 
// preg_filter function
$string = 'November 01, 2018';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1} 02, $3';
  
// print result 
echo preg_filter($pattern, $replacement, $string);
?>


Output:

November 02, 2018

Program 2 :




<?php
  
// PHP program to illustrate preg_filter function
$subject = array('1', 'GFG', '2', 
        'Geeks', '3', 'GCET', 'Contribute', '4'); 
$pattern = array('/\d/', '/[a-z]/', '/[1a]/'); 
$replace = array('X:$0', 'Y:$0', 'Z:$0'); 
  
echo "Returned Array by preg_filter";
print_r(preg_filter($pattern, $replace, $subject)); 
?>


Output:

Returned Array by preg_filterArray
(
    [0] => X:Z:1
    [2] => X:2
    [3] => GY:eY:eY:kY:s
    [4] => X:3
    [6] => CY:oY:nY:tY:rY:iY:bY:uY:tY:e
    [7] => X:4
)

Reference: http://php.net/manual/en/function.preg-filter.php

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32516 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12014 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS