preg_replace_callback
Perform a regular expression search and replace it with a callback
preg_replace_callback()
function gives an expression and a callback function and returns a string where all matches of the expression are replaced by the substring returned by the callback function.
Calculate the number of letters for all words in a sentence:
<?php function countLetters ( $matches ) { return $matches [ 0 ] . '(' . strlen ( $matches [ 0 ] ) . ')' ; } $input = "Welcome to W3School.com.cn!" ; $pattern = '/[a-z0-9\.]+/i' ; $result = preg_replace_callback ( $pattern , 'countLetters' , $input ) ; echo $result ; ?>
Try it yourself
preg_replace_callback ( pattern , replacements , input , limit , count )
parameter | describe |
---|---|
pattern | Required. A regular expression or array of regular expressions indicating what to search for. |
replacements |
Required. A callback function that returns a replacement. The callback function has a parameter that contains an array of matches. The first element of the array contains matches to the entire expression, while the rest contain matches to each group in the expression. |
input | Required. A string or array of strings that are replaced on it. |
limit |
Optional. The default is -1, indicating no limit. Sets the limit on the number of replacements that can be made in each string. |
count | Optional. After the function is executed, this variable will contain a number indicating how many replacements have been made. |