- preg_replace_callback: documentation ( source)
<?php
function updateYear(string $text, int $newYear): string
{
$year = null;
$result = preg_replace_callback(
'/(\-)(\d\d\d\d)/',
function (array $matches) use ($newYear, &$year): string {
$year = (int) $matches[2];
return $matches[1] . (string) $newYear;
},
$text
);
return "Replaced {$year} in '{$text} => '{$result}'";
}
echo updateYear('(c) 1970-2022', 2023) . PHP_EOL;
echo updateYear('(c) 1999-2022', 2023) . PHP_EOL;