PHP
7
Вклад в тег
class MyCallback {
private $key;
function __construct($key) {
$this->key = $key;
}
public function callback($matches) {
return sprintf('%s-%s', reset($matches), $this->key);
}
}
$output = 'abca';
$pattern = '/a/';
$key = 'key';
$callback = new MyCallback($key);
$output = preg_replace_callback($pattern, array($callback, 'callback'), $output);
print $output; //prints: a-keybca-key
$output = 'abca';
$pattern = '/a/';
$key = 'key';
$output = preg_replace_callback($pattern, function ($matches) use($key) {
return sprintf('%s-%s', reset($matches), $key);
}, $output);
print $output; //prints: a-keybca-key