The preg_replace_callback Function

The preg_replace_callback function performs search by regular expression and replacement using a callback function. The first parameter accepts a regular expression, the second - a callback function, and the third - a string to process. The callback function receives an array of matches and must return a replacement string.

Syntax

phppreg_replace_callback(pattern, callback, subject, [limit], [count]);

Example

Let's replace all numbers in the string with their squares:

php<?php
  $str = 'Numbers: 2, 4, 6';
  $res = preg_replace_callback('/\d+/', function($matches) {
    return $matches[0] * $matches[0];
  }, $str);
  echo $res;
?>

Code execution result:

php'Numbers: 4, 16, 36'

Example

Let's convert all words to uppercase:

php<?php
  $str = 'hello world';
  $res = preg_replace_callback('/\b\w+\b/', function($matches) {
    return strtoupper($matches[0]);
  }, $str);
  echo $res;
?>

Code execution result:

php'HELLO WORLD'

Example

Let's add parentheses around each number:

php<?php
  $str = '1 2 3 4 5';
  $res = preg_replace_callback('/\d+/', function($matches) {
    return '('.$matches[0].')';
  }, $str);
  echo $res;
?>

Code execution result:

php'(1) (2) (3) (4) (5)'

See Also

  • the preg_replace function,
    which performs replacement by regular expression
  • the preg_match function,
    which performs search by regular expression