PHP preg_replace_callback() Function

P
PHP preg_replace_callback_array() Function
PHP preg_replace() Function

In this article, you will learn about preg_replace_callback() method in PHP. The preg_replace_callback() function in PHP returns a string where all matches of the expression are replaced with the substring returned by the callback function.

This function uses an expression and a callback function.

what is the syntax of the PREG_REPLACE_CALLBACK function in php?

preg_replace_callback(pattern, callback, input, limit, count)
ParameterDescription
patternRequired. A regular expression or array of regular expressions indicating what to search for
replacementsRequired. A callback function which returns the replacement.

The callback function has one parameter containing an array of matches. The first element in the array contains the match for the whole expression while the remaining elements have matches for each of the groups in the expression.
inputRequired. The string or array of strings in which replacements are being performed
limitOptional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string
countOptional. After the function has executed, this variable will contain a number indicating how many replacements were performed
PHP PREG_REPLACE_CALLBACK() method

examples of the PREG_REPLACE_CALLBACK function

Example 1. In this example, we count letters in all of the words in a sentence.

<?php
function countLetters($matches) {
  return $matches[0] . '(' . strlen($matches[0]) . ')';
}

$input = "Welcome to W3Schools.com!";
$pattern = '/[a-z0-9\.]+/i';
$result = preg_replace_callback($pattern, 'countLetters', $input);
echo $result;
?>
PHP preg_replace_callback_array() Function
PHP preg_replace() Function

Tutor Network

Share this

Learn PHP from A to Z