lang/php/ PregReplace


Callback

The docs. Summary:

preg_replace_callback(
    string|array $pattern,
    callable $callback,
    string|array $subject,
    int $limit = -1,
    int &$count = null,
    int $flags = 0
): string|array|null

Example (method)

<?php
class A {
  function process($text) {
    $result = preg_replace_callback('/pattern/',[$this,"mycallback"],$text);
    return $result;
  }
  function mycallback(&$m) {
    return "[[".$m[0]."]]";
  }
}
$a = new A();
$b = $a->process("See what it does to the pattern in here.");
echo "$b\n";

Example (function)

<?php
function process($text) {
  $result = preg_replace_callback('/pattern/',"mycallback",$text);
  return $result;
}
function mycallback($m) {
  $r = "[[".$m[0]."]]";
  return $r;
}
$b = process("See what it does to the pattern in here.");
echo "$b\n";