204 of 410 menu

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

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

Example

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

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

Code execution result:

'Numbers: 4, 16, 36'

Example

Let's convert all words to uppercase:

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

Code execution result:

'HELLO WORLD'

Example

Let's add parentheses around each number:

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

Code execution result:

'(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
byenru