In this article, you will learn about preg_filter method in PHP.
The preg_filter() function returns a string or array of strings in which matches of the pattern have been replaced with the replacement string.
If the input is an array, this function returns an array. If the input is a string then this function returns a string.
preg_replace function is similar to PREG_FILTER() with one difference: When no match is found in an input string, the string will not be used in the return value. If the input is a string the function returns null instead of an array.
what is the syntax of the PREG_FILTER function in php?
preg_filter(pattern, replacement, input, limit, count)
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
replacement | Required. A string which will replace the matched patterns. It may contain backreferences |
input | Required. A string or array of strings in which the replacements are being performed |
limit | Optional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string |
count | Optional. After the function has executed, this variable will contain a number indicating how many replacements were performed |
examples of the PREG_FILTER function
Example 1. In this example, wrap numbers in brackets in a list of strings.
<?php
$input = [
"It is 5 o'clock",
"40 days",
"No numbers here",
"In the year 2000"
];
$result = preg_filter('/[0-9]+/', '($0)', $input);
print_r($result);
?>