PHP preg_replace_callback_array() Function

PHP preg_split() Function
PHP preg_replace_callback() Function

In this article, you will learn how to replace an array of strings in PHP. The preg_replace_callback_array() function in PHP returns a string or an array of strings in which matches of a set of regular expressions are replaced with the return value of a callback function.

what is the syntax of the PREG_REPLACE_CALLBACK_ARRAY function in php?

preg_replace_callback_array(patterns, input, limit, count)
patternRequired. An associative array which associates regular expression patterns to callback functions.

The callback functions have one parameter which is 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

examples of the PREG_REPLACE_CALLBACK_ARRAY function

Example 1. In this example, we show how many letters or digits are found in each word in a sentence.

function countLetters($matches) {
  return $matches[0] . '[' . strlen($matches[0]) . 'letter]';

function countDigits($matches) {
  return $matches[0] . '[' . strlen($matches[0]) . 'digit]';

$input = "There are 365 days in a year.";
$patterns = [
  '/\b[a-z]+\b/i' => 'countLetters',
  '/\b[0-9]+\b/' => 'countDigits'
$result = preg_replace_callback_array($patterns, $input);
echo $result;
PHP preg_split() Function
PHP preg_replace_callback() Function

Add comment

Tutor Network

Share this

Learn PHP from A to Z