preg_filter
preg_filter(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null
Performs a preg_replace-style substitution but returns only the elements that were replaced — on arrays it is filter-and-replace in one.
C C23
#include <stdio.h>
#include <regex.h>
#include <string.h>
// filter + replace in one pass: keep only strings that match, with every
// digit replaced by 'N' (the preg_filter semantics, hand-rolled)
static int preg_filter_like(const char *in, char *out) {
regex_t re;
regcomp(&re, "[0-9]", REG_EXTENDED);
int keep = (regexec(&re, in, 0, NULL, 0) == 0); // the "filter" half
regfree(&re);
if (!keep) {
out[0] = '\0';
return 0; // no match: dropped
}
for (size_t i = 0; i <= strlen(in); i++) { // the "replace" half
out[i] = (in[i] >= '0' && in[i] <= '9') ? 'N' : in[i];
}
return 1;
}
int main(void) {
const char *subjects[] = {"a", "1", "b", "2"};
for (int i = 0; i < 4; i++) {
char out[32];
int kept = preg_filter_like(subjects[i], out);
printf("%s -> %s\n", subjects[i], kept ? out : "(dropped)");
}
return 0;
}
a -> (dropped) 1 -> N b -> (dropped) 2 -> N
C++ C++26
#include <iostream>
#include <regex>
#include <string>
#include <vector>
int main() {
std::vector<std::string> subjects{"a", "1", "b", "2"};
std::regex re("[0-9]");
std::vector<std::string> result;
for (const auto& s : subjects) {
// regex_search is the "filter" half; regex_replace is the "replace" half;
// combining both is the preg_filter equivalent
if (std::regex_search(s, re)) {
result.push_back(std::regex_replace(s, re, "N"));
}
}
for (const auto& s : result) std::cout << "kept: " << s << "\n";
return 0;
}
kept: N kept: N
C# v11.0.100
using System.Linq;
using System.Text.RegularExpressions;
var subjects = new[] { "a", "1", "b", "2" };
// Where (filter) then Select+Replace: no single preg_filter equivalent
var result = subjects
.Where(s => Regex.IsMatch(s, @"\d"))
.Select(s => Regex.Replace(s, @"\d", "N"));
Console.WriteLine(string.Join(",", result));
N,N
Go v1.27.4
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`[0-9]`)
subjects := []string{"a", "1", "b", "2"}
var result []string
// MatchString (filter) + ReplaceAllString (replace): preg_filter equivalent
for _, s := range subjects {
if re.MatchString(s) {
result = append(result, re.ReplaceAllString(s, "N"))
}
}
fmt.Println(result)
}
[N N]
Java v27.0.1
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern digit = Pattern.compile("[0-9]");
String[] subjects = {"a", "1", "b", "2"};
List<String> result = new ArrayList<>();
// find() (filter) + replaceAll() (replace): preg_filter equivalent
for (String s : subjects) {
if (digit.matcher(s).find()) {
result.add(digit.matcher(s).replaceAll("N"));
}
}
System.out.println(result);
}
}
[N, N]
JavaScript v26.13.1
const subjects = ["a", "1", "b", "2"];
// filter (test) then map+replace: no single preg_filter equivalent
const result = subjects
.filter((s) => /\d/.test(s))
.map((s) => s.replace(/\d/g, "N"));
console.log(result);
[ 'N', 'N' ]
PHP v8.6.0
$subjects = ['a', '1', 'b', '2'];
// preg_replace returns EVERY element (matched ones substituted, others kept)
echo "preg_replace: ", json_encode(preg_replace('/\d/', 'N', $subjects)), "\n";
// preg_grep only filters, never substitutes — note the original keys are kept
echo "preg_grep: ", json_encode(preg_grep('/\d/', $subjects)), "\n";
// preg_filter filters AND substitutes: unmatched elements are dropped
echo "preg_filter: ", json_encode(preg_filter('/\d/', 'N', $subjects)), "\n";
// with a single string subject it behaves exactly like preg_replace
echo "string: ", preg_filter('/\d/', 'N', 'a1b2'), "\n";
preg_replace: ["a","N","b","N"]
preg_grep: {"1":"1","3":"2"}
preg_filter: {"1":"N","3":"N"}
string: aNbN
Python v3.15.2
import re
subjects = ["a", "1", "b", "2"]
# filter (re.search) + re.sub: no single preg_filter equivalent
result = [re.sub(r"\d", "N", s) for s in subjects if re.search(r"\d", s)]
print(result)
['N', 'N']
Rust v1.99.1
use regex::Regex; // regex crate
fn main() {
let re = Regex::new(r"[0-9]").unwrap();
let subjects = vec!["a", "1", "b", "2"];
// is_match (filter) + replace_all (replace): preg_filter equivalent
let result: Vec<String> = subjects
.iter()
.filter(|s| re.is_match(s))
.map(|s| re.replace_all(s, "N").into_owned())
.collect();
println!("{:?}", result);
}
["N", "N"]
TypeScript v26.13.1
const subjects: string[] = ["a", "1", "b", "2"];
// filter (test) then map+replace: no single preg_filter equivalent
const result = subjects
.filter((s) => /\d/.test(s))
.map((s) => s.replace(/\d/g, "N"));
console.log(result);
[ 'N', 'N' ]
Language differences
C: no built-in regex substitution — combine regexec (filter) with hand-written character substitution (replace) to get the preg_filter semantics.
C++: combine std::regex_search (filter) + std::regex_replace (replace); no single-function equivalent.
C#: Where (filter) + Regex.Replace (replace); .NET has no combined API.
Go: MatchString (filter) + ReplaceAllString (replace).
Java: find() (filter) + replaceAll() (replace).
JavaScript: filter(test) + map(replace); the /g flag replaces every match within one string.
PHP: the replace/grep/filter trio — preg_replace on an array returns everything (matches substituted, non-matches kept verbatim); preg_grep only filters, never substitutes; preg_filter filters AND substitutes (unmatched elements are dropped). All three preserve the original keys in the returned array (which is why the grep/filter JSON above is object-shaped); on a single string subject preg_filter is exactly preg_replace — arrays are where it earns its keep.
Python: re.search (filter) + re.sub (replace); no single-function equivalent.
Rust: is_match (filter) + replace_all (replace), with into_owned turning the Cow<str> into an independent String.
TypeScript: same as JS.